mo********@yahoo.com wrote:
In C++ FAQ (15.5), I see this code:
int i = 0;
while (std::cin >x) { // RIGHT! (reliable)
++i;
// Work with x ...
}
but I don't know how can while loop end? ostream &operator >>(...)
return ostream &. how can that ever end the while loop? Is it because
there is hidden operator to cast to int? I cannot figure out, please
help?
Either std::istream or one of its base classes overloads operator bool.
(Making it implicitly convertible to a bool). The overload returns a
value indicating whether the stream has experienced any sort of failure
(such as eof).
So, the process is, operator >returns a reference to a stream. while
wants a bool, so the reference is converted to a bool (via the operator
bool function), this reveals the state of the stream and either allows
the loop to continue or causes it to terminate.
--
Alan Johnson