当我运行程序时,文件中的最后一个数据会显示两次。
#include<stdio.h>?//heder
#include<conio.h>//header
int main(){//main
int cn,clas;//variable declaration
char fn[15],ln[15],pn[10],adds[15];//variable declaration
float mr;//variable declaration
int i=1;//variable declaration
FILE *fp;//file pointer declaration
fp=fopen("student.txt","r");// opening a file
if (fopen("student.txt","r") == NULL) {
printf("Error: file pointer is null.");
return 0;
}
while(! feof(fp) ){//here the program reads the data from file
fscanf(fp,"%d",&cn);
fscanf(fp,"%s",&fn);
fscanf(fp,"%s",&ln);
fscanf(fp,"%d",&clas);
fscanf(fp,"%s",&adds);
fscanf(fp,"%s",&pn);
fscanf(fp,"%f",&mr);
//from here the data is printed on output string
printf("%d",cn);printf("\n");
printf("%s",fn);printf("\n");
printf("%s",ln);printf("\n");
printf("%d",clas);printf("\n");
printf("%s",adds);printf("\n");
printf("%s",pn);printf("\n");
printf("%f",mr);printf("\n");
printf("\n");
printf("\n");
}
}
我所访问的文件就是这个 this is the file that i accesed 程序给出的输出就是这个 最后一个重复 this is output 请帮帮我这个
答案 0 :(得分:0)
通常情况下,这只是值得评论,但在这种情况下,它恰恰是问题的根本原因。您错误地使用了feof
。在读取失败之后,feof
才会返回true。所以你的程序读取最后一行,然后当feof
返回false时转到循环的顶部。然后第一个scanf失败(并且它们都失败),然后使用仍然可以从循环的前一次迭代获得的数据执行printf,然后feof返回true并且循环终止。您必须检查每个scanf的返回值,如果其中任何一个无法读取数据,则必须退出循环。或者,更好的是,避免使用scanf,使用fread并解析缓冲区。