Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does reading file with while loops work in C++?

Why is it possible to read a file using a while loop such as

while (file >> variable)

Or

while (getline(xx, yy))

Do the >> and getline functions return boolean values ?

like image 358
mahela007 Avatar asked Dec 23 '12 08:12

mahela007


2 Answers

The stream operators evaluate to a reference to the stream itself. This allows chaining e.g. file >> variable >> variable >> variable.

When you combine it with the fact that the stream object is convertible to boolean (whose value is true iff no error flags are set) and, yes, you get that effect.

like image 150
Lightness Races in Orbit Avatar answered Sep 21 '22 10:09

Lightness Races in Orbit


If we have something like:

a file with data:

11 
22 
13
45
19

and then a C++ file:

int variable;
int count = 0;
while(!file.eof())
{
    count ++;
    file >> variable;
}
cout << "there are  " << count << " numbers in the file";

the output from this would be 6, because when we read 19, eof is false, only when we try to read the NEXT number does eof get set. We could fix this by moving the count++ to an if-statement, so we have if (file >> variable) count++; instead. But that gets quite clumsy.

If we instead do:

while(file >> variable)
{
   count++;
}

the loop exits when when we try to read the next number after 19.

Edit: Fix "reason why it counts wrong" to clarify that eof() is set after "unsuccessful read".

Should also point out that the while(!file.eof()) doesn't work well with bad input. Say we have the above code, but the input is 11 22 aa ... - eof() doesn't get set when the input is aa. The input just stops and returns an error. But since eof() is still false [we can technically read more from the file, as long as we don't try to read it as a number]. So this leads to an infinite loop! The while (file >> variable) solution avoids this problem - of course, you may still need to add some extra code to say "I expected a number here, and I got something else". But you don't have to worry about the loop going on forever reading nothing.

like image 45
Mats Petersson Avatar answered Sep 21 '22 10:09

Mats Petersson