C 在结构化数组中向数组输入值时出现分段错误

C 在结构化数组中向数组输入值时出现分段错误,c,arrays,input,C,Arrays,Input,我对C的结构有一个问题。我想写一个程序,从grades.txt读取数据,保存到结构化数组并打印出来。所以我在下面写了一段代码。 程序c 而grades.txt的内容是 grades.txt 你必须跳过第一行。你增加i,但不要跳过第一行。您使程序将字符读取为整数。 也许是类似于 fscanf(fp1,"%s %s %s %s %s %s", ....(strings here) ); 首先,在if块中,您没有检查fopen的返回值,因为如果文件不存在,您的代码不应该在fp1上执行进一步的操作。因

我对C的结构有一个问题。我想写一个程序,从grades.txt读取数据,保存到结构化数组并打印出来。所以我在下面写了一段代码。 程序c

而grades.txt的内容是

grades.txt


你必须跳过第一行。你增加i,但不要跳过第一行。您使程序将字符读取为整数。 也许是类似于

fscanf(fp1,"%s %s %s %s %s %s", ....(strings here) );

首先,在if块中,您没有检查fopen的返回值,因为如果文件不存在,您的代码不应该在fp1上执行进一步的操作。因此,请检查返回值,如下所示

fp1 = fopen("grades.txt","r");
if(fp1 == NULL) {
   /* error handling */
}
其次,正如@paul所提到的,在while循环中使用fscanf&将fscanf的返回值检查为

您犯了一些愚蠢的错误,因为printf语句中有一个额外的%d,您可以在使用-Wall标志编译时解决或观察到它。 这个


有六个%d,但只提供了5个参数,请删除额外的%d,因为只有5个参数。

请参阅:。此外,您还需要在调用fopen后添加错误检查。此外,您忘记跳过第一行,该行包含文本,而不是数字。
ID       Q1 Q2 Q3 Q4 Total
20131122 20 14 18 22    74
20132400 16 23 11 19    69
fscanf(fp1,"%s %s %s %s %s %s", ....(strings here) );
fp1 = fopen("grades.txt","r");
if(fp1 == NULL) {
   /* error handling */
}
while(fscanf(fp1,"%d %d %d %d %d %d", &a[i].number, &a[i].q[0], &a[i].q[1], &a[i].q[2], &a[i].q[3], &a[i].total) == 6 ) { /* 6 is the no of read item */
      printf("%d %d %d %d %d \n", a[i].number,a[i].q[0], a[i].q[1], a[i].q[2], a[i].total);
      i++; 
}
printf("%d %d %d %d %d %d\n", a[i].number,a[i].q[0], a[i].q[1], a[i].q[2], a[i].total);