1

I have a text file called scores.txt with the following data:

John T Smith 90
Eric K Jones 103
Ram S Krishnan 25
Marie A Bell 50

I am trying to read the data from this file and print it using the following C++ code:

ifstream input;
input.open("scores.txt");
string firstName;
char mi;
string lastName;
int score;

while (input) {
    input>>firstName>>mi>>lastName>>score;
    cout<<firstName<<" "<<mi<<" "<<lastName<<" "<<score<<endl;
}

input.close();
cout<<"Done"<<endl;

The output is:

John T Smith 90
Eric K Jones 103
Ram S Krishnan 25
Marie A Bell 50
Marie A Bell 50

Why is the last line (Marie A Bell 50) being printed twice? How can I prevent this from happening?

Siddhartha
  • 209
  • 1
  • 7
  • You failed to check for the return value of your input operation. – Kerrek SB Dec 08 '15 at 21:51
  • @KerrekSB What do you mean by that? Sorry, I'm new to C++. – Siddhartha Dec 08 '15 at 21:52
  • You're saying "Let `firstName` have the value that's next on the input", but you never admit the possibility in your thinking that there may not be a next value. This is a conceptual failure logic. – Kerrek SB Dec 08 '15 at 21:53

1 Answers1

6

It's because just after you read the file's last line, input is not yet at end of file. Your program enters the while loop a fifth time, reads input (which set it to its end of file state), does not alter your variables and prints them.

A way (amongst many) to avoid this is to write something like

while (input >> var1 >> var2)
{
    std::cout << var1 << "," << var2 << std::endl;
}
YSC
  • 34,418
  • 7
  • 80
  • 129