首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

坐待解答 文件读取为什么会多读一行

2013-06-25 
坐等解答 文件读取为什么会多读一行ifstream ifs(D:\\2.txt)string temp1, temp2while(!ifs.eof()){ifs

坐等解答 文件读取为什么会多读一行
ifstream ifs("D:\\2.txt")
string temp1, temp2;
while(!ifs.eof())
{
  ifs>>temp1;
  ifs>>temp2;
  cout<<temp1;
  cout<<temp2;
}
D:\\2.txt文件中有三行数据,每行两个字符串,为什么最后一行的字符串会被显示两遍   文件读取
[解决办法]
文件有3行,要第4次读才会返回EOF,所以最后一个temp2并没有读取成功,最后一行的内容是temp2上一次的内容.


#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream ifs("2.txt");
string temp1, temp2;

temp1 = "111";
temp2 = "222";
while (!ifs.eof()) {
ifs >> temp1;
ifs >> temp2;  // 这里的返回不成功
cout << temp1 << temp2;

/*
if (ifs >> temp1)
 cout << temp1;

if (ifs >> temp2)
cout << temp2;
*/
}

return 0;
}

[解决办法]

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(){
ifstream ifs("D:\\2.txt");
string temp1, temp2;
//要读4次才会返回EOF。。改成这样就可以了。。
while(ifs>>temp1>>temp2)
{
cout<<temp1<<' ';
cout<<temp2<<endl;
}

return 0;
}

[解决办法]
不要使用
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;
 //...
}
类似的例子还可以举很多。

热点排行