feof函数很奇怪,本人曾经栽倒在这上面,下面来看程序:

#include<iostream>
using namespace std;

int main()
{
	FILE *fp = fopen("myData.txt", "w");
	fprintf(fp, "1 2  \n3 4 5 6   \n"); // \n为换行
	fclose(fp);

	int a;
	fp = fopen("myData.txt", "r");
	while(!feof(fp))
	{
		fscanf(fp, "%d", &a);
		cout << a << endl;
	}
	fclose(fp);

	return 0;
}

       程序结果居然是:

1
2
3
4
5
6
6
      

       上网搜索一下,就知道其中的原因. 个人建议,尽量不要在不了解feof的情况下用它. 上面的程序最好改为:

#include<iostream>
using namespace std;

int main()
{
	FILE *fp = fopen("myData.txt", "w");
	fprintf(fp, "1 2  \n3 4 5 6   \n"); // \n为换行
	fclose(fp);

	int a;
	fp = fopen("myData.txt", "r");
	while(EOF != fscanf(fp, "%d", &a))
	{
		cout << a << endl; // 读取文件中所有的整数
	}
	fclose(fp);

	return 0;
}


     结果为:

1
2
3
4
5
6

     总之, feof很怪异,留个心吧。

 


本文转载:CSDN博客