I have a problem with the structure of C. I want to write a program which reads data fromgrades.txt
, save it to the structured array and print it. So I wrote a code below this.
program.c
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp1;
fp1 = fopen("grades.txt","r");
int i = 0,j;
typedef struct
{
int number;
int q[4];
int total;
} student;
student a[101];
while(feof(fp1) == 0)
{
if(i==0) i++;
else
{
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);
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);
i++;
}
}
fclose(fp1);
return 0;
}
However, it prints garbage values and segmentation fault error.
778121006 7632239 778121006 7632239 0 -1399308296
Segmentation fault
And the content of grades.txt is
grades.txt
ID Q1 Q2 Q3 Q4 Total
20131122 20 14 18 22 74
20132400 16 23 11 19 69