[英]Unexpected behaviour of cin for bool
我正在尝试使用cin
输入布尔类型数组。 如果输入像0111100010001000
这样给出,而不是运行所有迭代(在我的输入中是16),它将终止并打印一些垃圾值,但是如果输入像0 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0
它按预期工作。
#include<cstdio>
#include<cstring>
#include<iostream>
#define FRND 2001
using namespace std;
int main(){
bool mutualFriend[FRND][FRND];
int noOfFriends = 0;
cin >> noOfFriends;
for (int i = 0; i < noOfFriends ; i++){
for (int j = 0; j < noOfFriends; j++){
cin >> mutualFriend[i][j];
}
}
for (int i = 0; i < noOfFriends ; i++){
for (int j = 0; j < noOfFriends; j++){
cout << mutualFriend[i][j] << " ";
}
cout << endl;
}
return 0;
}
cin.clear()
可以解决我的问题。
请解释为什么在第一种情况下跳过循环。
标准的§22.4.2.1.2[facet.num.get.virtuals] / p6中指定了operator>>
解析bool
参数输入的方式:
如果
(str.flags()&ios_base::boolalpha)==0
则输入将long
,除非将值存储在val
,该值根据以下确定:如果要存储的值为0
然后存储false
。 如果值为1
则存储true
。 否则,将存储true
并将ios_base::failbit
分配给err。
因此,如果给它0111100010001000
,它将首先尝试将其解析为long
,从而为您提供一个很大的数字(显然不是1
)。 然后,处理的第二步将true
存入bool
并设置failbit
。
cin的默认定界符为空格,因此当您从值10101中读取时,它将视为一个大整数。
而是使用.get()读取单个字符
for (int i = 0; i < noOfFriends ; i++){
for (int j = 0; j < noOfFriends; j++){
mutualFriend[i][j] = (cin.get() == '1');
}
}
TC解释了流向bool
工作方式,总共消耗了long
, 0
> false
, 1
> true
,否则为true
但设置了failbit
。
对于常规数字输入,C ++具有用于十进制输入的std::dec
,用于八进制(基数8)的std::oct
,用于十六进制(基数16)的std::hex
,但是奇怪的是对于二进制数则没有。 无法将数字的多位二进制表示形式直接读取为整数类型。
您要做的就是一次读取一个字符,然后自己转换为二进制:
`char c;`
...
if (cin >> c && (c == '0' || c == '1'))
mutualFriend[i][j] == c != '0';
else
throw std::runtime_error("failure to parse binary digit from stream");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.