來源:http://blog.vckbase.com/bruceteen/archive/2005/06/29/8952.html
1
]#include < iostream >
2
#include < limits >
3
using namespace std;
4
5
int main()
6
{
7
int n = 0 ;
8
while ( ! (cin >> n) )
9
{
10
cin.clear();
11
cin.ignore( numeric_limits < streamsize > ::max(), ' \n ' ); // cin.sync()
12
cout << " Error " << endl;
13
}
14
15
cout << " ------------\n " << n << endl;
16
return 0 ;
17
}
18
19
]#include < iostream > 2
#include < limits > 3
using namespace std;4
5
int main()6
{7
int n = 0 ;8
while ( ! (cin >> n) )9
{10
cin.clear();11
cin.ignore( numeric_limits < streamsize > ::max(), ' \n ' ); // cin.sync() 12
cout << " Error " << endl;13
} 14
15
cout << " ------------\n " << n << endl;16
return 0 ;17
} 18
19
cin.clear()恢復正確標志位
cin.ignore流中錯誤的數據拋棄掉
為了進一步查看輸入流的狀態,可以通過以下代碼測試:
http://blog.csdn.net/SearchLife/archive/2008/12/10/3491768.aspx
#include <iostream>
using namespace std; 
int main() 

{
int a;
cin>>a;
cout<<cin.rdstate()<<endl;
if(cin.rdstate() == ios::goodbit)

{
cout<<"輸入數據的類型正確,無錯誤!"<<endl;
}
if(cin.rdstate() == ios_base::failbit) 
{
cout<<"輸入數據類型錯誤,非致命錯誤,可清除輸入緩沖區挽回!"<<endl;
}
}



我們定義要輸入到的變量是整型,但如果我們輸入了英文字母或者漢字,那就會發生錯誤,cin里有個方法能檢測這個錯誤,就是cin.rdstate();
當cin.rdstate()返回0(即ios::goodbit)時表示無錯誤,可以繼續輸入或者操作,若返回4則發生非致命錯誤即ios::failbit,則不能繼續輸入或操作.而cin.clear則可以控制我們此時cin里對這個問題的一個標識.語發如下:
cin.clear(標識符);
標識符號為:
goodbit 無錯誤
Eofbit 已到達文件尾
failbit 非致命的輸入/輸出錯誤,可挽回
badbit 致命的輸入/輸出錯誤,無法挽回
若在輸入輸出類里.需要加ios::標識符號
