今天用文件输入时发现了一个值得注意的问题。
先看程序:
#include <stdlib.h> #include <stdio.h> int main(void) { FILE*in=fopen("1.txt","r"); int a,b; if(in==NULL) { printf("error:cannot open infile !\n"); return -1; } while(!feof(in)){ fscanf(in,"%d %d",&a,&b); printf("%d %d\n",a,b); } system("pause"); return 0; }
再看文件1.txt中的内容:
1 2
3 4
5 6
你也许会认为输出的结果会是:
1 2
3 4
5 6
你有可能发现结果会是:
1 2
3 4
5 6
5 6
怎么最后一对数据出现两次?
因为程序从文件输入时一共输入了4次 比计划的3次多了一次。你打开文件1.txt检查发现数据只有3行
1 2
3 4
5 6
其实5 6的最后面还加了一个回车,回车是看不到的。
当程序从文件读入5 6后,文件还有一个回车符,所以这时文件还没结束。!feof(in)的值为真。所以接着从文件输入,
而文件指针此时指向的文件位置处没有两个int数据,所以输入失败 a和b还保存这上一次输入的值。就会出现上面看到的结果。
其实,只要利用fscanf()自身的返回值判断就没有问题。
程序改为如下:
#include <stdlib.h> #include <stdio.h> int main(void) { FILE*in=fopen("1.txt","r"); int a,b; if(in==NULL) { printf("error:cannot open infile !\n"); return -1; } while(fscanf(in,"%d %d",&a,&b)==2){ printf("%d %d\n",a,b); } system("pause"); return 0; }
这时输出结果就入我们所料了。
这时我写邻接表时犯的错误,找了好久才找到!