if(cin) while(cin) 以及 while(cin>>x) 條件表達式中的 流對象cin 的用法

先寫個引用(google的,我看書看不這麼仔細,^-^)

 

Eckel/Allison's "Thinking in C++ Volume Two: Practical Programming" (the footnote on page 167):

"It is customary to use operator void *() in preference to operator bool()

because the implicit conversions from bool to int may cause surprises,
should you incorrectly place a stream in a context where an integer
conversion can be applied. The operator void*() function will only be
called implicitly in the body of a Boolean expression."

 

 

<1>

先簡單說說 if(cin) while(cin)的用法:


1。cin 流對象,有標誌位,當流輸入有問題的時候,標誌位就會on/off
2。cin 有成員函數,返回標誌位的狀態,比如cin.fail(), 如果輸入流有問題,就會根據標誌位返回 true
3。cin 有個重載操作符 ios::operator void* ,在布爾表達式中,流對象cin會調用該重載,把流對象隱式轉換爲指針。當cin.fail返回true的時候, 轉換爲NULL指針。

例子:
int v1,v2;
cin>>v1>>v2;
如果輸入 1 g (回車),
g 不是數字,爲不正確輸入,輸入流出錯,cin.fail 值爲true,此時,
if(cin) 中,cin 被轉爲NULL指針,不執行條件語句塊
同樣,while(cin)結束循環

 

<2>

那麼,while(cin>>x)又如何呢?

流對象中,>>是重載操作符,它的返回值是流對象本身的引用。所以

while(cin>>x) 同下面兩句

cin>>x;

while(cin);

是等效的。

 

-------

以上。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章