假设有一文件in.data,其内容为123,现要读取并输出其内容,程序如下:
#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;
}
3.
#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;
}// input from console
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char c;
while(scanf("%c", &c)!=EOF)
{
cout<<c;
}

return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
while(scanf("%c", &c)!=EOF)
{
cout<<c;
}
return 0;
}
本文探讨了使用C++从文件中读取字符时遇到的一个常见问题:为何最后一个字符会被重复输出,并提供了三种不同的解决方案来避免这个问题。

1693

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



