c - 打印用户输入数组

标签 c arrays

有人能给我提示为什么这不打印数组吗?我不知道我的打印功能出了什么问题。在将其他部分添加到代码中之前,我想确保它正常工作。我猜我没有正确设置数组,这就是为什么没有打印出任何内容。

#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);
}
}

最佳答案

你这里有不止一个错误。 首先,你应该因为这一行而得到一个越界异常 (使用高级编程语言):

stuId[NUMSTU] = studentId;

stuId 是一个初始长度为 NUMSTU 的数组。 您尝试在 NUMSTU 中访问它,即使它具有可访问的插槽 仅在 0(NUMSTU-1) 之间。

您可能想做这件事:

stuId[stuCount] = studentId;

并且在打印中,您只是再次打印数组的位置 然后再次。而不是:

print("%d", stuId);

做:

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

哦,是的,还有第三个错误:

int stuCount = 0;
int totStu = 0;

stuCounttotStu 已声明为全局变量 (意味着每个函数都可以访问它们)。 您正在做的是定义具有相同名称的新变量, 但不能被其他函数访问。 因此,您应该决定它们是全局性的还是本地性的。 无论如何,你应该将其更改为:

stuCount = 0;
totStu = 0;

现在应该可以工作了。

关于c - 打印用户输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833672/

相关文章:

c - 重申链表(银行家算法)

java - 从数组中获取最后一个元素

arrays - 在单独的 ViewController 中编辑 tableView 条目,并将编辑后的数据传回 tableView

python - 如何删除列表组合列表中列表的特定元素?

c - 不使用 math.h 库的 Sin 函数

c - 如何从utf8字符串中获取字符

c - 当数组在声明时初始化时,什么会导致 C 代码崩溃,但如果通过循环清零则不会崩溃?

c - C 应用程序如何使用 gem5 在多个内核上工作?

arrays - 在awk中,当遇到新字符串时如何增加数组索引?

arrays - 在elasticsearch中的字符串数组中搜索精确字段