Search code examples
c++while-loopifstream

C++: I don't understand how this while loop works


I was looking at some questions on here that shows you how to read from a txt file, and then assign anything in it to separate variables. The answer used a while loop that looked like this...

ifstream file(“file.txt”);

int var1;
int var2;
int var3;

while (file >> var1 >> var2 >> var3)
{
    /* do something with name, var1 etc. */
    cout << var1 << var2 << var3 << “\n”;
}

My question is, what is happening in that while loop that allows it assign those variables the right value? I know that it works, because I used it, but I just don't understand how it works.

Here's the link I was looking at, just in case anybody wanted to also look at it. C++: Read from text file and separate into variable

Thanks!


Solution

  • Basically, the "expression"(a) file >> var1 >> var2 >> var3 will attempt to read three values from the file stream and place them into the specified variables. It's basically no different than cin >> myVar on it's own (except that it's chanining the input to multiple variables).

    The value of that entire expression will be true if and only if all three values are read successfully.

    In that case, the loop body will execute, the three values will be printed out, and the loop will go back to the top and try to get the next three values.

    At the point where the expression evaluates as false (i.e., three values are not read), the loop will stop.


    (a) The actual pathway from someStream >> someVariable to a Boolean value involves a few steps within the stream class (the return value from operator>> being converted to a Boolean with operator bool) but the above explanation should be good enough for most purposes.