1

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.

2 Answers 2

2
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);

Sign up to request clarification or add additional context in comments.

Comments

1

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].

5 Comments

Let me help you now that you helped me: you should use %20 not %21 or the limit is useless (null terminator string).
@Jean-FrançoisFabre That is true. I wasn't thinking of the null terminator in specifying.
Just notice that you can use, but don't need parens in &student->stuid.
On the other hand, if you change test to an array of pointers, you now need to allocate memory. So it's best to keep it as it is and use &test[i].stuid.
I tried following your answer, but on my end it ends up only adding the last line on the file 3 times, rather than all 3 lines. Do I put the for loop inside the while fscanf?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.