C++: 使用ifstream与getline()。

问题描述 投票:8回答:4

检查这个程序

ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();

文件Hey.txt里有很多字符。超过1000个

但我的问题是为什么在第二次我尝试打印行。它没有得到打印?

c++ file-io fstream getline
4个回答
11
投票

根据C++的参考文献(此处) getline设置了 ios::fail 当count-1字符被提取出来时。你必须调用 filein.clear(); 其间 getline() 调用。


41
投票

从流中读行的习惯性方法是这样的。

{
    std::ifstream filein("Hey.txt");

    for (std::string line; std::getline(filein, line); )
    {
        std::cout << line << std::endl;
    }
}

注意:

  • close(). 习惯性地使用C++就能为你解决资源管理问题。

  • 使用免费的 std::getline而不是流成员函数。


1
投票

正如Kerrek SB所说的那样,有两种可能:1) 第二行是空行2) 没有第二行,所有超过1000个字符都在一行,所以第二行是空行。getline 没有什么可以得到。


1
投票
#include<iostream>
using namespace std;
int main() 
{
ifstream in;
string lastLine1;
string lastLine2;
in.open("input.txt");
while(in.good()){
    getline(in,lastLine1);
    getline(in,lastLine2);
}
in.close();
if(lastLine2=="")
    cout<<lastLine1<<endl;
else
    cout<<lastLine2<<endl;
return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.