cin 在 while 循环中
cin inside a while loop
我写了一个简单的代码:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a >> b) //Note the cin inside while loop
{
cout << a << b << "\n";
}
}
我们知道 while
循环仅在表达式计算 true
(1
) 或 false
(0
) 时起作用。
为什么 cin
正在评估 true
和 false
。
此外 当我输入数字时 while 循环 运行 以及当我输入非数字时停止的情况如何 ?真假如何判断?
当你写cin >> a
时,你实际上使用的是std::istream::operator>>
,根据参考资料here,这个运算符returns和istream&
object reference,并把右边的变量(reference)作为它的参数。这就是你如何链接它的方式:cin >> a >> b
.
从另一个角度看这个cin >> a >> b
链,当分解时,就是这两步:
- 第一步,
cin >> a
returns 一些中间值,假设它是 x
。 (你实际上可以尝试 auto x = cin >> a
.
- 第二步,你在做
(cin >> a) >> b
,当我们使用这个中间值x
时,我们可以写成x >> b
.
所以这 x
到底是什么东西? x
这里与cin
保持相同的位置,它是istream&
类型的对象。
所以,当你说true
或者false
的时候,你其实是在说this是否返回了istream&
引用,引用了一个对象,是否是true
或 false
。当标准输出捕捉到 EOF 符号时,它将是 false
(比如当你在类似 unix 的系统中键入 Ctrl-C 时,或者当你读到文件末尾时)。
因此,您的代码可以扩展为
#include <iostream>
using namespace std;
int main()
{
int a, b;
auto x = cin >> a >> b
while (x)
{
cout << a << b << "\n";
}
}
如果您正在使用 IDE,例如 Visual Studio,您可以将鼠标指向变量 x
,它会提示您 x
的类型,并且那将是 istream&
.
此外,感谢 Bob__,这个 istream&
class 可以转换为 ios::operator bool
class,如 here ,无论是true
还是false
都代表了这个stream
的状态(ios_base::iostate
),所以,
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) {...}
or while(getline(stream, string)){...}
. Such loops execute the loop's body only if the input operation succeeded.
为了进一步理解,您应该阅读教科书中的运算符(重载)一章。
我写了一个简单的代码:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a >> b) //Note the cin inside while loop
{
cout << a << b << "\n";
}
}
我们知道 while
循环仅在表达式计算 true
(1
) 或 false
(0
) 时起作用。
为什么 cin
正在评估 true
和 false
。
此外 当我输入数字时 while 循环 运行 以及当我输入非数字时停止的情况如何 ?真假如何判断?
当你写cin >> a
时,你实际上使用的是std::istream::operator>>
,根据参考资料here,这个运算符returns和istream&
object reference,并把右边的变量(reference)作为它的参数。这就是你如何链接它的方式:cin >> a >> b
.
从另一个角度看这个cin >> a >> b
链,当分解时,就是这两步:
- 第一步,
cin >> a
returns 一些中间值,假设它是x
。 (你实际上可以尝试auto x = cin >> a
. - 第二步,你在做
(cin >> a) >> b
,当我们使用这个中间值x
时,我们可以写成x >> b
.
所以这 x
到底是什么东西? x
这里与cin
保持相同的位置,它是istream&
类型的对象。
所以,当你说true
或者false
的时候,你其实是在说this是否返回了istream&
引用,引用了一个对象,是否是true
或 false
。当标准输出捕捉到 EOF 符号时,它将是 false
(比如当你在类似 unix 的系统中键入 Ctrl-C 时,或者当你读到文件末尾时)。
因此,您的代码可以扩展为
#include <iostream>
using namespace std;
int main()
{
int a, b;
auto x = cin >> a >> b
while (x)
{
cout << a << b << "\n";
}
}
如果您正在使用 IDE,例如 Visual Studio,您可以将鼠标指向变量 x
,它会提示您 x
的类型,并且那将是 istream&
.
此外,感谢 Bob__,这个 istream&
class 可以转换为 ios::operator bool
class,如 here ,无论是true
还是false
都代表了这个stream
的状态(ios_base::iostate
),所以,
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.
为了进一步理解,您应该阅读教科书中的运算符(重载)一章。