if (cin >> x) - 为什么你可以使用那个条件?

if (cin gt;gt; x) - Why can you use that condition?(if (cin x) - 为什么你可以使用那个条件?)
本文介绍了if (cin >> x) - 为什么你可以使用那个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

整个夏天我一直在使用Accelerated C++"来学习 C++,但有一个我似乎不太理解的概念.

I have been using "Accelerated C++" to learn C++ over the summer, and there's a concept which I don't seem to understand properly.

为什么

int x;
if (cin >> x){}

相当于

cin >> x;
if (cin){}

通过查看代码,在我看来,我们正在使用 cin 作为变量.但是,我认为这是一个函数.当 x 具有我们在键盘中输入的任何值时,为什么我们可以这样使用 cin?

By looking at the code, it seems to me that we're using cin as a variable. But, I thought it was a function. Why can we use cin in this way when it is x that has whatever value we input into our keyboard?

推荐答案

cinistream 表示标准输入流.它对应于cstdiostdin.操作符 >>> 重载流返回对同一流的引用.流本身可以通过转换运算符在布尔条件中评估为真或假.

cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin. The operator >>overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.

cin 提供格式化的流提取.操作cin>>x;

cin provides formatted stream extraction. The operation cin >> x;

如果一个非数字值是一个整数,那么x"是一个整数将会失败进入.所以:

where "x" is an int will fail if a non-numeric value is entered. So:

if(cin>>x)

如果您输入的是字母而不是数字,将返回 false.

will return false if you enter a letter rather than a digit.

这个关于使用 C++ I/O 的技巧和窍门 的网站也会对您有所帮助.

This website on tips and tricks using C++ I/O will help you too.

这篇关于if (cin >> x) - 为什么你可以使用那个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)