while the stream infilevar is good execute the next block
read input - it may fail
do stuff - if input failed it gets executed anyway with odd results
go back to 1
1 2 3 4 5 6
while ( true )
{
if ( !(infilevar >> voornaam) )
break;
// ...
}
always execute the next block
read input and check for failure - infilevar >> voornaam returns true if after input infilevar is good
if checking failed exit from the while block
do stuff
go back to 1
The only difference between the two version is when you check the file state
The problem is that you execute the entire contents of the loop without regard to the success or failure of attempting to read a voornaam from the file.
1 2 3 4 5 6 7 8
while (infilevar) // Always true until after an attempt was made to read past EOF
{
char firstname[7];
infilevar >> firstname; // Success or failure happens here
// Now execute the rest of the loop even though the last input may have failed
...
}
The solution is to check for failure after reading but before the rest of the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while (true) // It doesn't matter here whether file is good or bad
{
char firstname[7];
// Try to get something from the file
infilevar >> firstname;
// Now it matters.
// Check to see if the last attempt to read the file worked or not.
// If not, then quit the loop.
if (!infilevar) break;
// Otherwise we continue with the rest of the loop
...
}
Bazzy's code just combined lines 6 and 11 into a single line:
1 2
// Try to get something from the file. On failure, quit the loop.
if (!(infilevar >> firstname)) break;