C++: Using ifstream with getline();

Mohamed Ahmed Nabil picture Mohamed Ahmed Nabil · Aug 26, 2012 · Viewed 97.3k times · Source

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?

Answer

Kerrek SB picture Kerrek SB · Aug 26, 2012

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.