if(cin>> x) - 为什么你可以使用那个条件? [英] if (cin >> x) - Why can you use that condition?

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

问题描述

我一直在使用加速C ++在夏天学习C ++,有一个我似乎不能理解的概念。



为什么

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



  cin>> X; 
if(cin){}



通过查看代码,我们使用cin作为变量。但是,我认为这是一个功能。为什么我们可以使用cin这种方式,当它有任何值我们输入到我们的键盘的任何值。

解决方案

cin 是类 istream ,表示标准输入流。它对应于 cstdio stdin 。对于流的运算符>> 重载返回对同一流的引用。流本身可以通过转换运算符在布尔条件中求值为true或false。



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



其中x如果非数字值为
,int将失败。因此:

  if(cin>> x)

$ b $ p

会返回 false b

本网站使用C ++ I / O的提示和技巧也会对您有所帮助。


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.

Why is

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

equivalent to

cin >> x;
if (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?

解决方案

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 provides formatted stream extraction. The operation cin >> x;

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

if(cin>>x)

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆