Search code examples
c++fileifstream

Reading txt line by line


I am reading a text file line by line in C++. I'm using this code:

while (inFile)
{
getline(inFile,oneLine);
}

This is a text file:

-------

This file is a test to see 
how we can reverse the words
on one line.

Let's see how it works.

Here's a long one with a quote from The Autumn of the Patriarch. Let's see if I can say it all in one breath and if your program can read it all at once:
Another line at the end just to test.
-------

The problem is I can read only the paragraph starts with "Here's a long etc..." and it stops "at once:" I couldn't solve to read all text. Do you have any suggestion?


Solution

  • The correct line reading idiom is:

    std::ifstream infile("thefile.txt");
    
    for (std::string line; std::getline(infile, line); )
    {
        // process "line"
    }
    

    Or the alternative for people who don't like for loops:

    {
        std::string line;
        while (std::getline(infile, line))
        {
            // process "line"
        }
    }
    

    Note that this works as expected even if the file couldn't be opened, though you might want to add an additional check if (infile) at the top if you want to produce a dedicated diagnostic for that condition.