C++: Using ifstream with getline();

女生的网名这么多〃 提交于 2020-05-09 19:17:25

问题


Check this program

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

The file Hey.txt has alot of characters in it. Well over a 1000

But my question is Why in the second time i try to print line. It doesnt get print?


回答1:


According to the C++ reference (here) getline sets the ios::fail when count-1 characters have been extracted. You would have to call filein.clear(); in between the getline() calls.




回答2:


The idiomatic way to read lines from a stream is thus:

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

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

Note:

  • No close(). C++ takes care of resource management for you when used idiomatically.

  • Use the free std::getline, not the stream member function.




回答3:


As Kerrek SB said correctly There is 2 possibilities: 1) Second line is an empty line 2) there is no second line and all more than 1000 character is in one line, so second getline has nothing to get.



来源:https://stackoverflow.com/questions/12133379/c-using-ifstream-with-getline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!