C++: Using ifstream with getline();

前端 未结 4 1789
名媛妹妹
名媛妹妹 2021-02-03 12:34

Check this program

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

        
相关标签:
4条回答
  • 2021-02-03 12:37

    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.

    0 讨论(0)
  • 2021-02-03 12:42

    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.

    0 讨论(0)
  • 2021-02-03 12:48

    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.

    0 讨论(0)
  • 2021-02-03 12:48
    #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;
    }
    
    0 讨论(0)
提交回复
热议问题