stream flow inside while condition

Hello, I don't understand why this works:

1
2
3
4
5
while (ss >> a)
{
     v.push_back(a);
     ss >> ch;
}


where ss is a stringstream object, v a vector and ch a char. What I don't understand is how it could work if (ss >> a) is not a condition but a statement.

Thanks.
It's a common and clever practice.
ss >> a returns a reference to the stream ss
while() expects a bool expression.
So the compiler looks to see if it can convert a stream to a bool and finds this: http://www.cplusplus.com/reference/ios/ios/operator_bool/. Note that it returns "whether an error flag is set"

So in general, if you use a stream where the compile expects a bool, it will result in true if the stream is okay and false if the stream has an error.
The >> is an operator. Operators are used in expressions. Expressions return a value.
The == is an operator too. Expression foo == bar happens to return a boolean value.

Q: What is the return type of expression ss >> a?
A: http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
istream&; a reference to ss


Q: How does istream evaluate to bool?
A: http://www.cplusplus.com/reference/ios/ios/operator_bool/
Topic archived. No new replies allowed.