我有一個名爲「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;
}
請看[爲什麼「while(!feof(file))」總是錯的?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)寫這個循環是'while(fscanf(...) == 5){printf(「%s \ n」,test [i] .name);我++; }' –
我會檢查出來,但爲什麼條件== 5 ?! – utdlegend
請閱讀[手冊頁](https://msdn.microsoft.com/en-us/library/cb5kac8b.aspx)for'fscanf',然後再採取一步。 –