cin对于bool的意外行为
Unexpected behaviour of cin for bool
我试图使用cin
在bool类型数组中输入。如果输入像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()
可以解决我的问题。
请解释为什么在第一个场景中跳过循环。
operator>>
解析bool
参数输入的方式在§22.4.2.1.2 [facet.num.get]中指定。[虚拟]/p6的标准:
因此,如果您给它如果
(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读取时…它认为它只是一个大int。
使用.get()来读取单个字符
for (int i = 0; i < noOfFriends ; i++){
for (int j = 0; j < noOfFriends; j++){
mutualFriend[i][j] = (cin.get() == '1');
}
}
<p已经解释了流式传输到
bool
的工作方式,概括地说,long
被消耗,0
> false
, 1
-> true
,否则true
,但failbit
设置。
对于一般的数字输入,c++有std::dec
用于十进制输入,std::oct
用于八进制输入(以8为基数),std::hex
用于十六进制输入(以16为基数),但奇怪的是没有用于二进制输入。不能将数字的多位数二进制表示形式直接读入整型。
你要做的是每次读取一个字符,然后自己转换成二进制:
`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");
相关文章:
- 从udp接收帧对于人脸识别来说太慢
- 在C++中对T*类型执行std::move的意外行为
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 对于set上的循环-获取next元素迭代器
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 对于结构,表达式必须是可修改的ivalue
- 处理除以零会导致<csignal>意外行为
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 对于循环变体比较
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 使用vscode调试时,GDB意外退出
- 对于C++,方括号中的标题必须总是在引号中的标题之上吗
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- cin对于bool的意外行为