我正在尝试从文件中读取数据并将数据保存到结构数组中。但是,我不知道该怎么做。
结构是这样的
struct Student students {
int stuid;
char name[21];
double grade;
}
文本文件是这样的
1,76.50,Joe Smith
2,66.77,John Campbell
3,88.99,Jane Common
我试过的代码是这样的
//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)
我不确定如何将数据保存到数组中,因为我所采用的方式只会保存到第一个元素并且永远不会继续。我是否在读取文件的 while 语句中循环? 我是否制作另一个结构或临时变量来读取文件然后循环传输它?我对此不知所措,希望得到任何启发。
最佳答案
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;
}
调用 int n = loadgrade(test, fp);
关于c - 使用 fscanf 从文件读取并保存到 struct c 语言的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952556/