C 之 cin 與 !cin 的原理分析

2021-07-13 19:05:58 字數 1509 閱讀 5708

在判斷檔案開啟成功與否或是連續從流中讀取資料時,就要用到對流對像的操作,比如if(!cin) 或是 whie(cin) 等等。

** while(cin>>val),我們都知道 cin 是乙個流物件,而》運算子返回左邊的流物件,也就是說 cin>>val 返回 cin,於是 while(cin>>val)就變成了 while(cin),問題就變成了乙個流物件在判斷語句中的合法性。

不管是 while(cin)還是 if(cin),都是合法的,為什麼呢?我們自己定義乙個類,然後定義該類的物件,然後使用 if 語句來判斷它是不合法的。這說明,流物件具有某種轉換函式,可以將乙個流物件轉換成判斷語句可以識別的型別。

開啟 iostream.h 檔案,找到 cin 的定義,發現是來自於 istream.h,其中的模板類basic_istream 繼承自 basic_ios,開啟 basic_ios 的定義,發現它有兩個過載函式。operator void *() const 和 bool operator!() const。這兩個函式使得流物件可作為判斷語句的內容。

operator

void*() const

//轉化函式

bool

operator!() const

結論:1、operator void () const; 函式在 while(cin)或是 if(cin)時被呼叫,將流物件轉換成 void 型別。2、bool operator!() const; 函式在 while(!cin)或是 if(!cin)時被呼叫,將流物件轉換成 bool 型別。需要指出的是,上述兩個型別轉換都是隱式的。

因此,可以簡單的理解呼叫過程為:

while(cin) *****>

while(!cin.fail()) //

while the stream is ok

while(!cin) *****>

while(cin.fail()) //

while the stream is not ok

簡單測試:

#include

using

namespace

std;

class a

~a() {}

operator

void * () const

bool

operator!()const

};int main()

輸出結果:

通過除錯可以看到if(a)呼叫的就是operator void * () const這個函式

if(!a)呼叫的bool operator!()const。

C 之cin的使用

cin建有乙個緩衝區,即輸入緩衝區。一次輸入過程是這樣的,當一次鍵盤輸入結束時會將輸入的資料存入輸入緩衝區,而cin函式直接從輸入緩衝區中取資料。正因為cin函式是直接從緩衝區取資料的,所以有時候當緩衝區中有殘留資料時,cin函式會直接取得這些殘留資料而不會請求鍵盤輸入,這就是為什麼有時會出現輸入語...

C 對C的擴充套件之cin與cout

一 cin c 語言 include include include include using namespace std int main c 中的cin,cout 均是類物件,c中的scanf和printf均是函式。其中scanf,gets,fgets 包括cin均是不安全的,當輸入大於29個...

C與C 學習 cin與cout

二 cout 總結cin與cout是c 中的輸入和輸出函式,使用時需要新增標頭檔案 include iostream 和 using namespace std 相比c語言 cin 與 cout 不需要像 scanf 和 printf 那樣指定輸入和輸出格式,也不需要取位址運算子 就可以直接輸入或輸...