C编程文件处理数据的打印两次



当我运行程序时,文件中的最后一个数据显示了两次。

#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");                     
  }
}

我提到的文件是 这是我经过的文件程序给出的输出是最后一个重复 这是输出请帮助我这个

通常,这仅值得评论,但是在这种情况下,这正是问题的根本原因。您错误地使用了feoffeof直到读取失败后才返回true。因此,您的程序读取最后一行,然后在feof返回false时转到循环的顶部。然后,第一个SCANF失败(并且所有这些失败(,然后用循环的上一个迭代中可用的数据执行printf,然后feof返回true且循环终止。您必须检查每个SCANF的返回值,并在循环中脱离循环,如果它们没有读取数据。或者,更好的是,避免扫描,使用径向并解析缓冲区。

最新更新