首先注意:
1、每一個輸入(輸出)對象就代表一個輸入(輸出)流
2、輸入(輸出)對象中的流狀態成員標記了輸入(輸出)流當前的狀況,當eofbit、badbit、failbit三個標記位均為0時表示流狀態正常
3、一但某個或幾個標記位被設定,表示對象的流狀態出現相應狀況,流將對後面的輸入(輸出)關閉,直到標記位被清除
4、只有在流狀態良好的情況下,if或者while對該輸入(輸出)對象的判斷才能是Ture
接下來看看這個程式:
#include <iostream>
using namespace std;
int main()
{
int input;
while (cin >> input)
{
cout << input << endl;
cout << "rdstate()函數的傳回值: " << cin.rdstate() << endl;
cout << "三個標記位返回的傳回值: " << cin.fail() << cin.bad() << cin.eof() << endl;
cout << "goodbit標記位的傳回值: " << cin.good() << endl;
cout << endl;
}
cout << "rdstate()函數的傳回值: " << cin.rdstate() << endl;
cout << "三個標記位返回的傳回值: " << cin.fail() << cin.bad() << cin.eof() << endl;
cout << "goodbit標記位的傳回值: " << cin.good() << endl;
if (!cin)
cout << "input error" << endl;
else
cout << input << endl;
system ("pause");
return 0;
}
當輸入為:“123 124 158 137a”時,
輸出為:
具體分析如下:
123、124、158均被正常抽取,從rdstate()等 流狀態標記位測試函數的返回結果可以看出來。
當輪到137a進入程式時,抽取操作符將137成功抽取,將a留在輸入資料流中。抽取操作符“ >> ”返回cin對象,此時流狀態仍為正常,failbit、eofbit、badbit三個標記位的值均為0。然後while判定cin對象為true,使得進入迴圈輸出137及流狀態資訊。
接下來進入下一次迴圈,執行 cin >> input ; 語句:a為輸入資料流的第一個字元,a與input變數類型不符,導致cin流狀態的failbit標記位被置為1(goodbit標記位被置為0),這使得“ >> ”返回的cin對象自身檢測為False, 然後while判定cin對象為false,退出迴圈。而字元a,留在了輸入資料流中。
推出迴圈後輸出cin的流狀態,可以看出,rdstate()的結果是4,failbit標記位為1,goodbit標記位為0。
程式流程到了 if 語句,此時cin對象的failbit標記位已經被置為1(goodbit標記位被置0),if 判定cin對象為false ,那麼 !cin 為true,因此輸出input error。
再來看一看下一段代碼:
if (cin >> input)
cout << input << endl;
else
cout << "input error" << endl;
if (!cin)
cout << "input error" << endl;
else
cout << input << endl;
當輸入為567a時,輸出為:
567
567
原因:輸入資料流中的567被“ >> ”抽取到 input 中,因此抽取操作符“ >> ”返回的cin對象的流狀態成員正常。因此 !cin 為false,使得再一次輸出567。注意:字元a留在了輸入資料流。
但當代碼重複一次時:
if (cin >> input)
cout << input << endl;
else
cout << "input error" << endl;
if (!cin)
cout << "input error" << endl;
else
cout << input << endl;
//第一次代碼結束
if (cin >> input)
cout << input << endl;
else
cout << "input error" << endl;
if (!cin)
cout << "input error" << endl;
else
cout << input << endl;
//重複代碼結束
如果輸入567a,輸出是:
567
567
input error
input error
原因是:當第一次代碼正常完成後, 第二次代碼開始,輸入資料流中的第一個字元是a,a與input不匹配,“ >> ”無法抽取, 抽取操作符“ >> ”函數返回的cin對象,其failbit標記位被置為1(goodbit標記位被置為0) ,cin的自測為False,if 判定條件為false;且導致下一個if語句: if (!cin) 中, cin對象為false, !cin 為true。
真相是:只要抽取操作符“ >> ”能成功抽取輸入資料流中的資料,哪怕只是部分匹配,cin對象的流狀態成員(即標記位)不會被設定,流狀態仍將保持正常。
一旦輸入完全不匹配,“ >> ”無法進行任何抽取,返回的cin對象其failbit標記位置為1(goodbit標記位被置0),cin流狀態出現相應狀況 ,且在恢複之前,流將對後面的輸入關閉。
不對之處,敬請指教。