I have written a simple code:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a >> b) //Note the cin inside while loop
{
cout << a << b << "\n";
}
}
We know that while
loop functions only when the expression evaluates true
( 1
) or false
( 0
). How come cin
is evaluating true
and false
.
Also how is while loop running when I am entering a number and stops when I enter something non-digit ? How is it evaluating true and false?
When you writes cin >> a
, you are actually using the std::istream::operator>>
, according to the reference here , this operator returns an istream&
object reference , and took the right hand variable (reference) as its argument. This is how you can chain it like: cin >> a >> b
.
To see this cin >> a >> b
chain another way, when break down, it is this two steps:
cin >> a
returns some intermediate value, let's say it is x
. (You can actually try auto x = cin >> a
. (cin >> a) >> b
, when we use this intermediate value x
, we could write it as x >> b
. So what the hell is this x
? x
here stays a same position as the cin
, it is an object of istream&
type.
Therefore, when you talk about true
or false
, you are actually talking about whether this returned istream&
reference, refer to an object, whether it is true
or false
. It would be false
when the standard output catch an EOF sign (like when you type Ctrl-C in unix like system, or when you have read to the end of a file).
Your code, therefore, could be expanded as
#include <iostream>
using namespace std;
int main()
{
int a, b;
auto x = cin >> a >> b
while (x)
{
cout << a << b << "\n";
}
}
If you are using an IDE like Visual Studio, you could point your mouse at the variable x
, it would prompt you x
's type, and that would be an istream&
.
Also, thanks to Bob__, this istream&
class could be convert to an ios::operator bool
class, as is written here , whether it is true
or false
represents the state( ios_base::iostate
) of this stream
, it therfore,
makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as
while(stream >> value) {...}
orwhile(getline(stream, string)){...}
. Such loops execute the loop's body only if the input operation succeeded.
To further your understanding, you should read the operator (overloading) chapter in your textbook.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.