while

hi. I am a bit confuse about the while function.
for fstream, input files what does this mean?

1
2
3
4
5
6
7
ifstream input;
int x;

while(input >> x)
{
   //statements
}


in here what does the while here mean?
The bit within the parentheses next to the while() is an expression and all c++ expressions can be either true or false.

So, to say while (expression) means while the expression is true do whatever comes within the following braces {...}. And the expression (input >> x) is true as long as the ifstream object input
(e)xtracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of (x)


http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
A while loop is a loop: http://www.cplusplus.com/doc/tutorial/control/
1
2
3
4
while ( condition )
{
  // statements
}

1. Evaluate condition
2. IF false THEN exit the loop
ELSE
3a. execute statements
3b. continue from step 1


What is in the condition?
input >> x -- A stream input operation.

How does stream input operation evaluate to true or false?
The operator>> returns the stream object.

Okay then, reading a number from file into variable x is a "side-effect", and the actual condition is input.

How does a stream object evaluate to true or false?
Streams have an (implicit) operator for that too: http://www.cplusplus.com/reference/ios/ios/operator_bool/

If reading integer to x fails, then the stream has an error state and condition evaluates to false.

In other words the loop reads numbers from file (and executes statements) as long as it can -- up to the end of file or to non-numeric file content.
thanks for replying ^^
Topic archived. No new replies allowed.