【发布时间】:2016-12-25 15:37:18
【问题描述】:
我有一个名为“TEST.txt”的输入数据文件。它包含十名学生的三个不同考试的身份证号码、姓名和成绩。我正在尝试编写一个程序来读取这些输入数据,计算每个学生的考试平均值,然后将平均值> = 45.5的学生的id号、姓名、平均值再次写入名为“RESULT.TXT”的输出文件中" 使用结构。 我想我可以用我定义的结构读取我的输入数据。我想知道如何查找考试(一、二、三)的平均值,设置写入平均值的条件,以及将 ID、名称和平均值写入 RESULTS.TXT。 这是我到目前为止的代码。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct student{
char name[30];
int id;
int exam1;
int exam2;
int exam3;
}STUDENT;
int main(){
int sum=0;
int i=0;
double mean[10];
STUDENT test[10];
FILE *fRead;
fRead=fopen("TEST.txt","r+");
if((fRead=fopen("TEST.txt","r"))==NULL){
printf("File could not be opened\n");
}
while(!feof(fRead)){
fscanf(fRead,"%d%s%d%d%d",&(test[i].id),test[i].name,&(test[i].exam1),&(test[i].exam2),&(test[i].exam3));
printf("\n%s\n",test[i].name);
i++;
}
return 0;
}
【问题讨论】:
-
请参阅Why is “while ( !feof (file) )” always wrong? 编写该循环的方式是
while(fscanf(...) == 5) { printf("%s\n", test[i].name); i++; } -
我去看看,但是为什么条件==5?!
-
请阅读man page for
fscanf,然后再采取进一步措施。 -
最好(虽然并不总是使用)结构的定义和该结构的 typedef 分开。
-
发布的问题缺少某些关键信息。 IE。一些示例输入,一些预期输出
标签: c arrays structure file-writing file-processing