Kyle M
Kyle M

Reputation: 1

Reading data line by line from a text file

Each line of the text file has first name, last name, and a salary. Something along the lines of this:

john doe 4000

bob miller 9000

I want my program to take the first name, last name, and salary of each line and assign them to strings (or integers). I have tried this so far:

while (inFile){
    
    inFile >> firstName;
    inFile >> lastName;
    inFile >> grossPay;
    
    cout << firstName << " " << lastName << " " << grossPay << endl;
}

When it outputs the names and the salary, the last line of the text file gets output twice by the program. How can I fix this?

Upvotes: 0

Views: 70

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63946

After reading your last line, inFile is still in a valid state.

It's only when it tries to read more that your test would fail, but control has already entered the loop an additional time.

You want to test after reading.

while ( inFile >> firstName >> lastName >> grossPay ){
//      ^^ Now the test happens AFTER reading...
    cout << firstName << " " << lastName << " " << grossPay << endl;
}

Upvotes: 2

Related Questions