首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用bool变量判断是否要继续的有关问题

2012-10-06 
用bool变量判断是否要继续的问题C/C++ code#includeiostreamusing namespace stdintmain(){bool flagw

用bool变量判断是否要继续的问题

C/C++ code
#include<iostream>using namespace std;int  main(){    bool flag;    while(1)    {        cout<<"选吧(1/0)"<<endl;        cin>>flag;        if(flag)break;    }    return 0;}

非0的其他数都认为是true,但是如果我输入的是除1和0的其他数字的话,就会出现这个情况,为什么?


[解决办法]
探讨
C/C++ code

#include<iostream>
using namespace std;
int main()
{
bool flag;
while(1)
{
cout<<"选吧(1/0)"<<endl;
cin>>flag;
if(flag)break;
}
return 0;
}


非……

[解决办法]
比较同意7L的说法,一般说的0是false,非0是true,那是在表达式求值的时候的说法;在输入/输出的时候,应该是严格的0是false,1是true;所以当输入非0和1的东西的时候,会导致流异常。
C/C++ code
# include <iostream># include <ios>using namespace std;int main(){    bool flag;    ios::iostate status;    while (1)    {        cin.clear();        cin >> flag;        status = cin.rdstate();        if (status & ios::goodbit)            cout << "good" << endl;        if (status & ios::badbit)            cout << "bad" << endl;        if (status & ios::failbit)            cout << "fail" << endl;        if (status & ios::eofbit)            cout << "eof" << endl;        if (flag)            break;    }    return 0;} 

热点排行