新手:清除了错误标志位,为什么还是死循环!
- 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;}