C++: Using ifstream with getline();

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

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

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

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

Notes:

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

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


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.