简体   繁体   English

打印用户输入数组

[英]Printing user input array

Can someone give me a hint as to why this isn't printing the array? 有人可以提示我为什么不打印数组吗? I don't know what is wrong with my print function. 我不知道我的打印功能出了什么问题。 I want to make certain it's working correctly before I add in the other parts to my code. 在将其他部分添加到代码中之前,我想确定它是否可以正常工作。 I'm guessing I have not setup the array correctly & that's why nothing is printing out. 我猜我没有正确设置阵列,这就是为什么什么都没打印出来的原因。

#define NUMSTU 50

#include <stdio.h>

//function prototype
void printdata();

//Global variables

int stuID[NUMSTU];
int stuCount;
int totStu;

int main ()
{
   int stuCount = 0;
   int totStu = 0;
   int studentID;
    //Prompt user for number of student's in class

    printf("Please enter number of student's in class:");
    scanf ("%d", &totStu);

   for (stuCount = 0; stuCount <totStu; stuCount++)
   {    
   //Prompt user for student ID number

   printf("\n Please enter student's ID number:");
  scanf("%d", &studentID);
  stuID[NUMSTU] = studentID;

  }

 //Call Function to print data
 printdata();

 return 0;
 }//end main


 void printdata(){

 //This function will display collected data
 //Input: Globals stuID[NUMSTU]
//Output: none



//Display column headers
printf("\n\n stuID\n");

//loop and display student ID numbers
for (stuCount = 0; stuCount <totStu; stuCount++){
printf("%d", stuID);
}
}

You have more than one mistake here. 您在这里有多个错误。 First, you should get an out of boundaries exception because of this line (in higher level programming languages): 首先,由于这一行(在高级编程语言中),您应该获得一个边界外异常:

stuId[NUMSTU] = studentId;

stuId is an array that has an initial length of NUMSTU . stuId是一个数组,其初始长度为NUMSTU You're trying to access it in NUMSTU even though it has accessible slots only between 0 and (NUMSTU-1) . 您正在尝试在NUMSTU访问它,即使它只有0(NUMSTU-1)之间的可访问插槽。

You probably wanted to do this thing: 您可能想这样做:

stuId[stuCount] = studentId;

and in the print, you're only printing the location of the array again and again. 在打印中,您只需要一次又一次地打印阵列的位置。 Instead of: 代替:

print("%d", stuId);

do: 做:

print("%d", stuId[stuCount]);

Oh yeah, and a third mistake, here: 哦,是的,还有第三个错误:

int stuCount = 0;
int totStu = 0;

stuCount and totStu were already declared as global variables (meaning that every function has access to them). stuCounttotStu已被声明为全局变量(意味着每个函数都可以访问它们)。 What you're doing is defining new variables that have the same name, but cannot be accessed by other functions. 您正在执行的操作是定义具有相同名称但不能被其他函数访问的新变量。 So you should decide whether they are global, or local. 因此,您应该确定它们是全局的还是本地的。 Anyway, you should change it to: 无论如何,您应该将其更改为:

stuCount = 0;
totStu = 0;

Now it should work. 现在应该可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM