用C++ ifstream 来读取.txt文件的时候,通常用
while(!inFile.eof()) {
// your code
}
但是这样往往会造成最后一行读取两遍。
其实可以这样做,
方式一:
(来自 小心为上:注意C++ fstream给你设下的陷阱 http://blog.csdn.net/yah99_wolf/article/details/5961998 )
1: std::ifstream file("test.txt");
2: std::string word;
3: double value;
4: while (file >> word >> value) {
5: // A word and a double value were both read successfully
6: }
7: if (!file.eof()) throw std::runtime_error("Invalid data from file");
方式二:ifstream文件尾最后一行读两次
http://hi.baidu.com/windey1988/item/ae2a24e5586643324ddcafa5
ifstream input_positive("train-pos.lst");
string input_str;
vector<string> positive_img_name;
while(input_positive)
{
getline(input_positive,input_str);
if(input_positive.fail())
break;
positive_img_name.push_back(input_str);
}
fail() 判断最后的一次读写操作是否成功;
方式三:在C++ 重复读取文件中的最后一行的解决办法
ifstream in;
int roomNo , capacity, count;
char sex;
string phone;
in.open("roomInfo.dat");
if(!in)
{
cerr<<"读房间信息失败, 请确定文件存在!"<<endl;
exit(0);
}
while(!in.eof())
{
in>>roomNo>>sex>>phone>>capacity>>count; // 将信息读入变量
roomsInfo.push_back(new room(roomNo, sex, phone, capacity, count));
in.get(); // 读取最后的回车符
if(in.peek() == '\n') break;
}
原文地址:http://blog.163.com/chen_dawn/blog/static/112506320136243827769/