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