Hello kmcfall,
while (!inFile.eof())
This can work, but it seems as though no one really teaches the proper way to use it.
Given a file:
Your code:
1 2 3 4 5 6 7 8 9 10
|
while (!inFile.eof())
{
inFile >> firstName >> lastName >> department >> monthsal >> percbonus >> taxperc;
float paycheck = ((monthsal * percbonus) + monthsal) - (taxperc * monthsal);
cout << "First Name: " << firstName << endl << "Last Name: " << lastName << endl <<
"Department: " << department << "Monthly Salary: " << monthsal << "Bonus: " << percbonus <<
"Tax: " << taxperc << "Paycheck: $" << paycheck << endl;
}
|
Works like this:
When you reach the while loop it first checks the condition. It evaluates to true because "eof" has not been set yet, so your next line reads "name 1" and processes the code returning to the while condition where it is still considered true and you enter the loop.
On this pass you read "name 2" and process it returning to the while condition where it is still considered true.
Next pass you enter the loop and read "name 3" and process it returning to the while condition.
Even though you have read the last name the condition is still considered true, so you enter the loop. This time there is nothing left to read, so the "eof" bit is set, but you are inside the while loop so you continue and either process what was left in the variable(s) or the variable(s) are set to zero or empty for strings and your output is incorrect.
Now that the "eof" bit is set the while condition will evaluate to "false" and the loop will end.
To properly use what you need try this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
inFile >> firstName >> lastName >> department >> monthsal >> percbonus >> taxperc;
while (!inFile.eof())
{
float paycheck = ((monthsal * percbonus) + monthsal) - (taxperc * monthsal);
cout << "First Name: " << firstName << endl << "Last Name: " << lastName << endl <<
"Department: " << department << "Monthly Salary: " << monthsal << "Bonus: " << percbonus <<
"Tax: " << taxperc << "Paycheck: $" << paycheck << endl;
inFile >> firstName >> lastName >> department >> monthsal >> percbonus >> taxperc;
}
|
This way when you check the while condition if the "eof" bit was not set you enter the while loop.
Doing the next read at the end if "eof" is set the while condition will fail at the proper time.
As a not the more accepted way to read a file of unknown size is:
while (inFile >> firstName >> lastName >> department >> monthsal >> percbonus >> taxperc)
. This way when the "eof" bit is set or any of the others the loop will fail.
Andy