如下小程式,如果輸入錯誤,不是整形,則輸入的這個數會留在緩存區,沒有被type取到,type輸出預設值或初始值或上次取得到的值(視初始化int type = 0這一句的位置,及編譯器優化時,把它放到了那裡,在如下程式中,GCC有可能把其提到循環的外面)。因為緩存區中有資料,是以cin不會等待使用者輸入,直接去緩存中讀取,發現緩存中的資料不是整形,便把這個資料流在緩存區中,如此反複。這有點類似epoll的ET模式,隻要緩存中有資料,沒有新的事件發生,則不會提示使用者再去讀,得使用者把緩存中的資料全部讀完才行。
void main( void )
{
while(1)
int type = 0;
cin >> type;
cout << type;
}
1、解決方案
1)錯誤的方法:通過fflush來重新整理流。
int fflush(FILE *stream);
如果 stream 指向輸出流或者更新流(update stream),并且這個更新流最近執行的操作不是輸入,那麼fflush 函數将把這個流中任何待寫資料傳送至宿主環境(host environment)寫入檔案。否則,它的行為是未定義的。
原文如下:
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
其中,宿主環境可以了解為作業系統或核心等。
由此可知,如果 stream 指向輸入流(如 stdin),那麼 fflush 函數的行為是不确定的。故而使用 fflush(stdin) 是不正确的,至少是移植性不好的。(VS支援,GCC不支援)
2)正确的解決方法:
(1)C版本
示例代碼

View Code
(2)C++版本

參考
<a href="http://www.cplusplus.com/reference/clibrary/cstdio/fflush/">http://www.cplusplus.com/reference/clibrary/cstdio/fflush/</a>
<a href="http://linux.die.net/man/3/fflush">http://linux.die.net/man/3/fflush</a>