Avatar of mike9380
mike9380Flag for United States of America asked on

Why does (!file.eof()) cause repeat of last input

The last line of input doubles in output  in the Bloodshed Dev-C++ compiler.

The input file is (employee.txt):

7453    40     18.00
1049   38     32.00
6734    39     22.00
4545    40     24.00
9707   38     35.00


#include <iostream> 
#include <fstream>
using namespace std;
int main() 
    int numberofemployees;
    int employeeid, hoursworked;
    float hourlyrate, grosspay, taxamount, netpay;
    const float TAXRATE=0.10;
    std::ifstream fin("employee.txt");
    while (!fin.eof() )
          fin >> employeeid >>hoursworked >> hourlyrate;
          std::cout<<"THE EMPLOYEE ID IS: "<<employeeid<<endl;
          std::cout<<"THE HOURS WORKED ARE: "<<hoursworked<<endl;
          std::cout<<"THE HOURLY RATE IS: "<<hourlyrate<<endl;
          std::cout<<"THE GROSSPAY IS: "<<grosspay<<endl;
          std::cout<<"THE TAX MOUNT IS: "<<taxamount<<endl;
          std::cout<<"THE NETPAY IS: "<<netpay<<endl;
          fin.close ();
          getchar ();
          return 0;

Open in new window


Avatar of undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

A little typo... of course the condition of the while should be while(!fin.eof() && !fin.fail()) ... forgot the '!'

The EOF condition is only met when you try to read PAST the end of the file. As long as you don't read past the end of the file, fin.eof() will not be true.

So, after processing the last data, the loop will start again (since fin.eof() is not true yet), and the read operation :

        fin >> employeeid >>hoursworked >> hourlyrate;

will try to read past the end of the file. This will make fin.eof() true, and moreover, reading the values will not succeed (since there aren't any to be read). Your code will happily print the last record again.

In other words, you need to check fin.eof() AFTER you tried to read from the file.

Or better yet, use getline to read the file one line at a time :
std::string line;
while (getline(fin, line)) {
  // do something with 'line'. You could for example use a stringstream to extract the values from it

Open in new window

Your help has saved me hundreds of hours of internet surfing.