0

I have the following C++ program:

ofstream output("scores.txt");
output<<"John"<<" "<<"T"<<" "<<"Smith"<<" "<<90<<endl;
output<<"Eric"<<" "<<"K"<<" "<<"Jones"<<" "<<103<<endl;
output.close();

ifstream input;
input.open("scores.txt");
string line;
while (!input.eof()) {
    getline(input, line);
    cout<<line<<endl;
}
input.close();

cout<<"Done";

The output is:

John T Smith 90
Eric K Jones 103

Done

Why is there a blank line between Eric K Jones 103 and Done?

Siddhartha
  • 209
  • 1
  • 7

1 Answers1

0

Structure your loop like this:

while (getline(input, line)) {
    cout<<line<<endl;
}

Your duplicate line is because the way your read loop is structured, once you read the last line the eof bit is not set yet because readline succeeded. Therefore, you iterate one more time, doing a readline that does set the eof bit, then you do cout<<line<<endl and that last endl is your extra blank line.

Adam
  • 15,548
  • 4
  • 47
  • 89