先看函数原型:
ios::clear
void clear ( iostate state = goodbit );Set error state flagsSets a new value for the error control state.
All the bits in the control state are replaced by the new ones; The value existing before the call has no effect.
If the function is called with goodbit as argument (which is the default value) all error flags are cleared.
The current state can be obtained with member function rdstate. http://www.cplusplus.com/reference/iostream/ios/clear/istream::sync
int sync ( );Synchronize input buffer with source of charactersSynchronizes the buffer associated with the stream to its controlled input sequence. This effectively means that the unread characters in the buffer are discarded.
The function only has meaning for buffered streams, in which case it effectively calls the pubsync member of thestreambuf object (rdbuf()->pubsync()) associated to the input sequence.
简而言之,clear是使流恢复正确的状态即清除流的错误状态,而sync则是来清除缓存区的数据流的。 如果流的状态没有恢复到正确的状态,那么即使清除了数据流也无法输入。 所以两个要联合起来使用。
#include<iostream> #include<stdexcept> using namespace std; int main() { int val; while(1) { cin>>val; if(cin.bad()) throw runtime_error("io stream corrupted"); if(cin.fail()) { cerr<<"bad data, try again" << endl; cin.clear(); //去掉后会输入一个错的后会一直输出bad data ,try again cin.sync(); //去掉后会输入一个错的后会一直输出bad data ,try again ,两个顺序不能颠倒 continue; } if(cin.good()) cout<<val<<endl; } return 0; }
清空输入缓冲区:
fflush(stdin);
std::cin.sync();
cin.ignore(1000, '\n') //忽略指定大小的内容,到制定字符结束忽略;常用来清空缓冲区
清空输出缓冲区:
fflush(stdout);
std::cout.flush();
endl也有清空输出缓冲区的功能.