Cin和布尔输入 [英] Cin and Boolean input

查看:101
本文介绍了Cin和布尔输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我想知道boolean数据下的cin函数如何工作. 举例来说:

bool a;
cin >> a;

我知道,如果我给出0或1,则我的数据a将为true或false. 但是,如果我再输入一个整数,甚至是一个字符串,会发生什么?

我正在处理以下代码:

#include <iostream>
using namespace std;

int main() {
 bool aSmile,bSmile;
 cout << "a smiling ?" << endl;
 cin >> aSmile;
 cout << "b smiling ?" << endl;
 cin >> bSmile;
 if (aSmile && bSmile == true)
 {
   cout << "problem";
 }
 else cout << "no problem";

 return 0;
}

如果我为两个布尔值都给出0或1,则没有问题. 但是,如果我给出另一个整数,则输出如下:

a smiling ?
9
b smiling ?
problem

不要求我向bSmile输入任何值,似乎跳过了"cin >> bSmile"行. 如果我给aSmile一个字符串值,也会发生同样的情况.

发生了什么事?

伙计们! :)

解决方案

来自 cppreference :

如果v的类型是bool并且未设置boolalpha,则如果要存储的值是0​,则存储false,如果要存储的值是,存储true,对于err分配任何其他值std::ios_base::failbit并存储true.

由于您输入的值不是01(甚至不是"true""false"),因此流在其流状态中设置了一个错误位,从而阻止了您进行任何进一步的输入. 在读入bSmile之前应先调用

clear().同样,这也是为什么您应该始终检查输入是否在流本身上有条件的情况下很好的理由.

I am new to C++ and I was wondering how the function cin in case of a boolean data works. Let's say for instance :

bool a;
cin >> a;

I understand that if I give 0 or 1, my data a will be either true or false. But what happens if I give another integer or even a string ?

I was working on the following code :

#include <iostream>
using namespace std;

int main() {
 bool aSmile,bSmile;
 cout << "a smiling ?" << endl;
 cin >> aSmile;
 cout << "b smiling ?" << endl;
 cin >> bSmile;
 if (aSmile && bSmile == true)
 {
   cout << "problem";
 }
 else cout << "no problem";

 return 0;
}

If I give the values of 0 or 1 for both boolean, there is no problem. But if I give another integer, here is the output :

a smiling ?
9
b smiling ?
problem

I am not asked to enter any value to bSmile, the line "cin >> bSmile" seems to be skipped. The same happens if I give a string value to aSmile.

What happened ?

Thx guys ! :)

解决方案

From cppreference:

If the type of v is bool and boolalpha is not set, then if the value to be stored is ​0​, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.

Since you entered a value that was not 0 or 1 (or even "true" or "false") the stream set an error bit in its stream state, preventing you from performing any further input.

clear() should be called before reading into bSmile. Also, this is a good reason why you should always check if your input suceeded with a conditional on the stream itself.

这篇关于Cin和布尔输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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