c - 使用 fscanf 从文件读取并保存到 struct c 语言的数组中

标签 c arrays 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 语句中循环? 我是否制作另一个结构或临时变量来读取文件然后循环传输它?我对此不知所措,希望得到任何启发。

最佳答案

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/

相关文章:

python - 数组的分布图

javascript - 使用 javascript/lodash 对特定键的相同值进行分组并对它们进行计数并将结果返回到数组

Golang,更改自定义客户端 MaxIdleConnsPerHost 的结构

c# - 如何解决这个 :Struct In Collection not changed

c - Udp readfrom直到结束

C 类型转换和加法优先级

c++ - 使用 cmake 编译日期和时间

c - 如何使用 scanf() 只捕获字符串

c++ - 使用队列在 OpenCV 中保存平移和旋转矩阵

我们可以使用 main、printf、scanf 来命名标识符吗?