正在看一本《C++从入门到实践》(秦广军 等编著 清华大学出版社 ISDN 978-7-302-20026-0)
其中,
第二章 数据类型 上机实践 31页的 2 ,按书中给出的内容
输入如下代码:
#include<iostream.h>
int main(void)
{
bool b;
bool a;
cin>>a;
cin>>b;
cout<<"!a="<<!a<<endl;
cout<<"a&&b : "<<(a&&b)<<endl;
cout<<"a||b :"<<(a||b)<<endl;
return 0;
}
但编译出来的时候,却显示如下错误:
error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'bool' (or there is no acceptable conversion)
: error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'bool' (or there is no acceptable conversion)
执行 cl.exe 时出错.
这是为什么呢?bool 型数据不能 接受 键盘输入 到cin?
到本书提供的论坛上问,得到如下解答:
“一般不直接使用cin给布尔类型进行赋值。至少我见到的大部分程序都是这样。
这个问题,我再确认一下。
”
http://www.wanjuanchina.net/thread-337-1-1.html
但如何改进呢?希望能实现手动输入,在输入的数据中进行处理。
在教材的帮助网站,管理员给出如下建议:
你可以设置一个中间变量。
中间变量获取输入的值。然后判断该值,然后决定赋值给布尔a、b的值。
这样就避免从键盘上给布尔a、b赋值了。
所以修改成如下代码,执行成功:
#include "stdafx.h"
#include <iostream.h>
int main(void)
{
bool a;
bool b;
int x;
int y;
cin>>x;
cin>>y;
a=x;
b=y;
cout<<"!a="<<(!a)<<endl;
cout<<"a&&b="<<(a&&b)<<endl;
cout<<"a||b="<<(a||b)<<endl;
return 0;
}