0

Possible Duplicate:
Reading from text file until EOF repeats last line

The cout output from my c++ program, prints to console but overlaps.

For instance:

while(pFile.good()){

  getline (pFile, pLine);
  cout<<pLine; 
}

This code, prints the last line, and some leftovers of the previous line.

I'm using vi on cygwin. This happened out of the blue. Did I change some setting?

Community
  • 1
  • 1
srrvnn
  • 609
  • 1
  • 11
  • 20

3 Answers3

2

getline() discards any newline character it encounters. To keep your code from merging all lines together into one big line, you need to do this instead:

cout << pLine << endl;

As chris pointed out, you also should use getline() as your while condition. Otherwise, the stream may be considered "good" now, but reach EOF when you call getline(). So try this loop:

while (getline(pFile, pLine)) {
    cout << pLine << endl;
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • I still fail to understand, why this change happened in the middle of something, if `getline()` behaves so all the time. – srrvnn Oct 08 '12 at 07:12
  • It may have to do with some environmental factors... perhaps the newline character used in the data changed, or something like that. – cdhowie Oct 08 '12 at 07:27
  • @esgee: It happens because the last successful call to getline() reads up-to but not past the end of file; Thus the EOF bit is not set. The call that sets the EOF bit reads nothing just moves the mark past the 'end of file'. – Martin York Oct 08 '12 at 08:02
1

The reason your last line is printed twice is because your last call to getline() failed, but you still printed pLine (even though its content is undefined).

while(pFile.good()){

  getline (pFile, pLine);  // What happens if this line fails.
                           // Like when you read **past** the end of file.
  cout<<pLine; 
}

The correct version of your code is:

while(pFile.good()){

  if (getline (pFile, pLine))
  {    cout<<pLine;
  } 
}

But this is usually written as:

while(getline (pFile, pLine))
{
   // The loop is only entered if the read worked.
   cout<<pLine; 
}

Remember that the last successful call to getline() reads up-to but not past the end of line. That mean the next call to getline() will fail and set the EOF bit.

Also note that your output is stinging together because you are not adding a '\n' seporator between your lines. Note: the getline() reads upto the next '\n' character but this termination character is not added to the string pLine.

Martin York
  • 257,169
  • 86
  • 333
  • 562
0

here u are writing at sameline because getline simply discards new line character,thats why u have to write <<endl

 while(pFile.good()){

      getline (pFile, pLine);
      cout<<pLine<<endl; 
    }
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70