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/


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值