C++:将 ifstream 与 getline() 结合使用;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12133379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:54:54  来源:igfitidea点击:

C++: Using ifstream with getline();

c++file-iofstreamgetline

提问by Mohamed Ahmed Nabil

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

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

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

但我的问题是为什么我第二次尝试打印线。它不打印?

回答by Kerrek SB

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.

  • 没有close()。C++ 在习惯使用时会为您处理资源管理。

  • 使用 free std::getline,而不是流成员函数。

回答by Roman Kutlak

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

根据 C++ 参考 ( here) getline 设置ios::fail提取 count-1 个字符的时间。您必须在通话filein.clear();之间进行getline()通话。

回答by BigBoss

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 getlinehas nothing to get.

正如 Kerrek SB 所说的那样,有两种可能性:1)第二行是空行 2)没有第二行,并且所有超过 1000 个字符都在一行中,因此第二行getline没有任何内容。

回答by Junyu lu

#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;
}