C++ 读取文件最后一行重复问题

出处:http://blog.163.com/chen_dawn/blog/static/112506320136243827769/

用C++ ifstream 来读取.txt文件的时候,通常用 

while(!inFile.eof()) {
  // your code
}

但是这样往往会造成最后一行读取两遍。

原因:

当infile读到最后一行(即读到EOF),while(infile)仍然判断为true,造成循环又一次运行。然而,因为infile已经读取完了整个文件,infile.getline读取失败,str变成空字符串。然而,由于源代码重写了第一个字符,使得str跳出空中断,所以它沿用上一次的内容。

其实可以这样做,

方式一:

 

(来自 小心为上:注意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;

posted @ 2013-10-31 20:18  搬砖吊死  阅读(866)  评论(0)    收藏  举报