cin 和布尔输入
我是 C++ 新手,我想知道函数 cin 在布尔数据的情况下如何工作.比如说:
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;
我明白,如果我给出 0 或 1,我的数据 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 ?
我正在编写以下代码:
#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 的值,则没有问题.但是如果我给另一个整数,这里是输出:
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
我没有被要求输入任何值到 bSmile,行 cin >>bSmile
似乎被跳过了.如果我给 aSmile 一个字符串值,也会发生同样的情况.
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.
发生了什么?
推荐答案
来自 cppreference:
如果v
的类型是bool
并且没有设置boolalpha
,那么如果要存储的值是 0
,false
被存储,如果要存储的值为1
,true
被存储,对于任何其他值std::ios_base::failbit
分配给 err
并存储 true
.
If the type of
v
isbool
andboolalpha
is not set, then if the value to be stored is ?0?
,false
is stored, if the value to be stored is1
,true
is stored, for any other valuestd::ios_base::failbit
is assigned toerr
andtrue
is stored.
由于您输入的值不是 0
或 1
(甚至是 "true"
或 "false"
) 流在其流状态中设置了一个错误位,阻止您执行任何进一步的输入.
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()
应该在读入 bSmile
之前调用.此外,这也是为什么您应该始终检查您的输入是否在流本身的条件下成功的一个很好的理由.
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.
相关文章