#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
fstream in;
in.open("in.data");
while(!in.eof())
{
in>>c;
cout<<c;
}in.close();
return 0;
}输出: 1233
为什么最后一个字符3会多输出一次呢?
因为当读取3之后,程序不会立刻检测到EOF,必须再次读取一次,而后才能识别到EOF,while循环执行了4次,所以会再次输出3。
可以作如下几种改进:
1.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
fstream in;
in.open("in.data");
in>>c;
while(!in.eof()) // 循环体执行了3次
{
cout<<c;
in>>c;
}
in.close();
return 0;
}2.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
fstream in;
in.open("in.data");
while(1)
{
in>>c;
if(in.eof())
break;
cout<<c;
}
in.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
while(scanf("%c", &c)!=EOF)
{
cout<<c;
}
return 0;
}

4834




被折叠的 条评论
为什么被折叠?



