while (std::cin >> x) why it works?

M

moleskyca1

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?
 
A

Alan Johnson

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.
 
M

Mark P

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?

Look right above this item, at 15.4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top