Reputation: 79
I am trying to read from a file and save the data into an array of struct. However I am at loss on how do I go about it.
The struct is like this
struct Student students {
int stuid;
char name[21];
double grade;
}
The text file is something like this
1,76.50,Joe Smith
2,66.77,John Campbell
3,88.99,Jane Common
The code I tried ended up something like this
//declaring the struct
struct Student test[3];
int loadgrade(struct Student* student, FILE* file) {
while (fscanf(file, "%d,%lf,%21[^\n]", &student.stuid, &student.grade, &student.name) == 3)
I am not sure how I would save the data into the array, as the way I have it will only save to the first element and never go on. Do I loop inside the while statement of reading the file? Do I make another struct or temp variable to read the file and then loop it to transfer it? I am at a loss on this and would appreciate any kind of enlightenment.
Upvotes: 1
Views: 1418
Reputation: 7308
So this is somewhat confusing because student
is a pointer, but the way to do this is as such
fscanf(file, "%d,%lf,%20[^\n]", &(student->stuid), &(student->grade), student->name);
Now if you want to fill the array test
, you can do this
for (int i = 0; i < 3; i++)
fscanf(file, "%d,%lf,%20[^\n]", &(test[i]->stuid), &(test[i]->grade), test[i]->name);
Having said that, you need to declare test
like this struct Student * test[3]
.
Upvotes: 1
Reputation: 40145
int loadgrade(struct Student* student, FILE* file) {
int i = 0;
while (fscanf(file, "%d,%lf,%20[^\n]", &student->stuid, &student->grade, student->name) == 3){
++student;
++i;
}
return i;
}
call int n = loadgrade(test, fp);
Upvotes: 2