简体   繁体   中英

reading from file using fscanf and saving into a array of struct c language

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM