關(guān)于輸入流的錯(cuò)誤
Posted on 2009-06-21 22:09 天邊藍(lán) 閱讀(533) 評(píng)論(0) 編輯 收藏 引用 所屬分類: cplusplus來源: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()恢復(fù)正確標(biāo)志位
cin.ignore流中錯(cuò)誤的數(shù)據(jù)拋棄掉
為了進(jìn)一步查看輸入流的狀態(tài),可以通過以下代碼測(cè)試:
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<<"輸入數(shù)據(jù)的類型正確,無錯(cuò)誤!"<<endl;
}
if(cin.rdstate() == ios_base::failbit) 
{
cout<<"輸入數(shù)據(jù)類型錯(cuò)誤,非致命錯(cuò)誤,可清除輸入緩沖區(qū)挽回!"<<endl;
}
}



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