[英]reading from file using fscanf and saving into a array of struct c language
我试图从文件中读取并将数据保存到struct数组中。 但是我对如何解决这个问题感到很茫然。
结构是这样的
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语句中循环? 我是否要创建另一个struct或temp变量来读取文件,然后循环它以传输它? 我对此感到茫然,并会欣赏任何启蒙。
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);
所以这有点令人困惑,因为student
是一个指针,但这样做的方式就是这样
fscanf(file, "%d,%lf,%20[^\n]", &(student->stuid), &(student->grade), student->name);
现在,如果要填充阵列test
,可以执行此操作
for (int i = 0; i < 3; i++)
fscanf(file, "%d,%lf,%20[^\n]", &(test[i]->stuid), &(test[i]->grade), test[i]->name);
话虽如此,你需要像这个struct Student * test[3]
一样声明test
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.