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

新手:清除了异常标志位,为什么还是死循环

2012-04-14 
新手:清除了错误标志位,为什么还是死循环!C/C++ code#include iostreamusing namespace stdint main(){

新手:清除了错误标志位,为什么还是死循环!

C/C++ code
#include <iostream>using namespace std;int main(){    cout<<"input a number:"<<endl;    int ival;    while(cin>>ival,!cin.eof()){        if(cin.bad()){            throw runtime_error("Can not fix");        }        if(cin.fail()){            cerr<<"Not the correct type needed"<<endl;            cin.clear(istream::failbit);                continue;        }    }    return 0;}            

  控制台一直输出Not the correct type needed!!为什么会是这样!!

[解决办法]
cin.clear(istream::failbit); 的意思是把标志位设为failbit

PS:C++ Primer第四版相关介绍有误,已多方证实
具体参见STL文档
[解决办法]
C/C++ code
#include <iostream>using namespace std;int main(){    cout<<"input a number:"<<endl;    int ival;    while(cin>>ival,!cin.eof()){        if(cin.bad()){            throw runtime_error("Can not fix");        }        if(cin.fail()){            cerr<<"Not the correct type needed"<<endl;            cin.clear();            //cin.clear(istream::failbit);            cin.sync();            continue;        }    }    return 0;} 

热点排行