问题
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?
回答1:
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:
- First step,
cin >> a
returns some intermediate value, let's say it isx
. (You can actually tryauto x = cin >> a
. - Second step, you are doing
(cin >> a) >> b
, when we use this intermediate valuex
, we could write it asx >> 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.
来源:https://stackoverflow.com/questions/42038373/c-cin-inside-a-while-loop