if(cin) while(cin) 以及 while(cin>>x) 条件表达式中的 流对象cin 的用法

本文介绍了C++中使用if(cin)和while(cin)来检查流对象状态的方法,并解释了为何选择使用operator void*()而非operator bool()。同时,文章还讨论了while(cin >> x)的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先写个引用(google的,我看书看不这么仔细,^-^)

 

Eckel/Allison's "Thinking in C++ Volume Two: Practical Programming" (the footnote on page 167):

"It is customary to use operator void *() in preference to operator bool()

because the implicit conversions from bool to int may cause surprises,
should you incorrectly place a stream in a context where an integer
conversion can be applied. The operator void*() function will only be
called implicitly in the body of a Boolean expression."

 

 

<1>

先简单说说 if(cin) while(cin)的用法:


1。cin 流对象,有标志位,当流输入有问题的时候,标志位就会on/off
2。cin 有成员函数,返回标志位的状态,比如cin.fail(), 如果输入流有问题,就会根据标志位返回 true
3。cin 有个重载操作符 ios::operator void* ,在布尔表达式中,流对象cin会调用该重载,把流对象隐式转换为指针。当cin.fail返回true的时候, 转换为NULL指针。

例子:
int v1,v2;
cin>>v1>>v2;
如果输入 1 g (回车),
g 不是数字,为不正确输入,输入流出错,cin.fail 值为true,此时,
if(cin) 中,cin 被转为NULL指针,不执行条件语句块
同样,while(cin)结束循环

 

<2>

那么,while(cin>>x)又如何呢?

流对象中,>>是重载操作符,它的返回值是流对象本身的引用。所以

while(cin>>x) 同下面两句

cin>>x;

while(cin);

是等效的。

 

-------

以上。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值