64,651
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream infile("a.txt");
string s1, s2;
while(!infile.eof())
{
infile>>s1>>s2;
cout<<s1<<s2<<endl;
}
}
这是a.txt的内容
yyy aw
xxx de
ttt de
结果输入的是
yyy aw
xxx de
ttt de
ttt de
我想问哈为啥最后一行会输出两次
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream infile("a.txt");
string s1, s2;
while(!infile.eof()) //当循环到文件内容已经读完的时候,文件读到末尾,这时候没到
//达你所想的eof,而是还会再往下执行
{
infile>>s1>>s2; //当到末尾了,而程序还要求读取多一次的时候,这才是真正的eof
cout<<s1<<s2<<endl; //而这次循环读不到任何值,s1,s2没有改变,所以还会输出最 //后一行
}
}
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。
while(!infile.eof())
{
infile>>s1>>s2; //读完最后一行的时候,infile.eof() == false, 接着再次执行本语句,此时文件已经读完,所以s1,s2的值并没有改变
cout<<s1<<s2<<endl;
}
while( infile>>s1>>s2)
{
cout<<s1<<s2<<endl;
}
ifstream ifs("a.txt");
string str;
while (getline(ifs, str))
{
cout << str << endl;
}