4

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?

Community
  • 1
  • 1
user987692
  • 43
  • 4
  • you are aware the you are overwriting the contents of `oneLine` every time that you read one line, so the only contents in `oneLine` after the while loop has terminated are of the last line. – PeterT Jan 23 '12 at 04:11
  • You didn't really include much code... – DilithiumMatrix Jan 23 '12 at 04:12

1 Answers1

7

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I really wish this was at the first page of every C++ book (for beginners) on the planet. – André Caron Jan 23 '12 at 04:11
  • 1
    @AndréCaron: It's the first entry in my file of "frequently pasted answers", if that's any consolation. – Kerrek SB Jan 23 '12 at 04:13
  • Hahahahah "frequently pasted answers"! I'll remember that one! – André Caron Jan 23 '12 at 04:16
  • @KerrekSB: that makes it a good candidate for a vote to close as exact duplicate. Unfortunately, there doesn't seem to be a canonical SO question that contains this canonical SO answer. – Ken Bloom Jan 23 '12 at 04:18
  • @KenBloom: There must be a thousand of those already... really, SO should have a mechanism to either create or mark existing questions as canonical, but as it stands, most of the questions are fairly obscure, while the answer is always the same... – Kerrek SB Jan 23 '12 at 04:22
  • @KerrekSB: my favorite version of this answer (and I'm biased, since I wrote it) is [this one](http://stackoverflow.com/a/6852956/197788), which demonstrates the exact same idiom in the IO library of pretty much every C-inspired language. – Ken Bloom Jan 23 '12 at 04:22
  • @KerrekSB: actually, this question is a perfect candidate for "canonical `getline()` question". – Ken Bloom Jan 23 '12 at 04:22