坐等解答 文件读取为什么会多读一行
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;
}