C++ 讀取檔案最後一行
用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/