c - 文件处理代码编译但不运行

标签 c file-io

我正在做的基本上是读取一个文件,将其保存到一个数组中,然后尝试打印它。但我的代码似乎有什么问题?

#include<stdio.h>
#include<string.h>

typedef struct{
    int studentNumber;      //struct declaration
    char name[31];
    float quizzes[8];
    float exams[3];
    float overallGrade;
    float standing;
}Student;

//function for transferring

void transfer(Student myList[]){
    int x=0;
    for (x=0; x<3;x++){
        printf("%d\n",myList[x].studentNumber);
        printf("%d\n",myList[x].quizzes);
        printf("%d\n",myList[x].exams);
    }

}
int main(){
    FILE *read = NULL; //creates a stream
    Student myList[50];
    int ctr=0;
    char buf[128];
    read = fopen("file.txt", "r"); //opens the file

    if(read==NULL)
        printf("FILE NOT FOUND!");
    else{
        while(!feof(read)){
            fgets(buf, sizeof(buf), read);  //reads first line
            sscanf(buf, "%d,", myList[0].studentNumber);
            fgets(buf, sizeof(buf), read);  //reads second Line
            sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d", &myList[ctr].quizzes[0],&myList[ctr].quizzes[1],&myList[ctr].quizzes[2],&myList[ctr].quizzes[3],&myList[ctr].quizzes[4],&myList[ctr].quizzes[5],&myList[ctr].quizzes[6],&myList[ctr].quizzes[7]);
            fgets(buf, sizeof(buf), read);  //reads third Line
            sscanf(buf, "%d,%d,%d", &myList[ctr].exams[0], &myList[ctr].exams[1],&myList[ctr].exams[2]);
            ctr++;  
        }
    }

    fclose(read);
    transfer(myList);

    return 0;       
}

该文件由三行主线组成。第一行是学号,第二行是测验,第三行是考试。该文件如下所示:

1234567
12,16,14,9,8,15,0,3
40,40,40
1237890
13,12,18,11,7,15,10,8
40,35,50
1232098
10,11,15,10,0,15,6,7
36,42,40

最佳答案

我不记得哪个旧编译器能够运行没有原型(prototype)的函数。但我会要求你使用:

void transfer(Student *);

并且还更改:

void transfer(Student myList[]);

void transfer(Student *myList)

此外,while 中的第一个 sscanf 应该是:

sscanf(buf, "%d,", &myList[ctr].studentNumber);

您使用了 0 而不是 ctr。

编辑: 除了使用的代码或格式之外,请不要对问题发表评论。

关于c - 文件处理代码编译但不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418943/

相关文章:

c - 使用递归反转字符串

c - 逐行读取csv文件并输出第五列用于在c中匹配

Java > JSch.如何从设置文件获取 SFTP 连接的属性?

python - python错误处理中的类型转换

matlab - 加快处理较大的二进制文件

c - C中指向数组赋值的指针

c - 为什么这个程序会在执行时崩溃?

c - 指向内存中指针的指针的大小

c++ - 删除 .. 在 boost filesystem::complete

java - 如何从路径生成 Guava ByteSource?