我如何使用fscanf从文件到c中的结构?

问题描述 投票:0回答:1

我无法将学生的信息从文件保存到结构,当我尝试打印我的结构时,它不起作用,我认为它应该起作用,但我不明白,为什么它不起作用。当我只像这样构造或使用文件时,它就可以工作。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//John exper 224(number) 99(grade)
//Alex King 199 36

struct Student{
    char name[100],surname[100],number[100];
    int grade[100];
};
readStudentsFromFile();
printStudents();
rankStudents();
calculateClassAverage();  


int main (){

    struct Student var[100];
    double co;
    readStudentsFromFile(&co);

}



readStudentsFromFile(double *co){
    char fileName[100],c;
    struct Student var[100];
    int i,count;
    printf("Enter file name: ");    
    gets(fileName);
    FILE *file;
    file=fopen(fileName,"r");
    
    if (file){
    count=1;    
        while(!feof(file))
        {
            c = fgetc(file);
            if(c == '\n')
            {
                count++;
            }
        }   
        for(i=0;i<count;i++){
            fscanf("%s %s %s %d",&var[i].name,&var[i].surname,&var[i].number,&var[i].grade);
        }
        }else{
            printf("Error: Unable to open file %s",fileName);
        }
    *co=count;
    printf("%s",var[1].name);
    fclose(file);
}


i need to save information to struct
c scanf
1个回答
0
投票

您的代码有很多问题,但似乎最大的问题是对

fscanf
的错误调用。 第一个参数需要是 FILE *,所以更改:

fscanf("%s %s %s %d", ...)

if (4 == fscanf(file, "%99s %99s %99s %d", ...)) 

此外,让

grade
成为一个整数数组而不仅仅是一个
int
似乎很奇怪。 对应于格式字符串中
%d
的 scanf 参数应该是
int
的地址。

© www.soinside.com 2019 - 2024. All rights reserved.