2015-04-17 92 views
0
#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 
    int num; 
    string str; 

    cout << "Input an integer a= "; 
    cin >> num; 
    cout << num << endl; 
    cout << "Input a string str= "; 
    fflush(stdin); 
    getline(cin,str); 
    cout << str << endl; 
    cout << "End program" << endl; 
    return 0; 
} 

輸出工作:函數getline後不fflush

Input an integer a= 1 
1 
Input a string str= 
End program 

fflush後getline()不工作。

+0

我不知道答案,但它不完全是getline()問題。如果你沒有先讀取'num',getline()就可以了。 –

+0

嘗試使用'getchar();'而不是'fflush(stdin);' –

+0

@酷人:謝謝,人:) – Lawliet

回答

0

fflush(stdin)是未定義的行爲,因爲fflush()的行爲僅爲輸出流定義。此外,這是「C風格」功能,不應與C++控制檯I/O結合使用。

相反fflush(),你可以通過你以前的CIN電話後直接加入cin.get()丟棄換行字符的:

cin >> num; 
cin.get(); 
0

時,程序會提示你「輸入一個整數=」,鍵入1和輸入,因此在cin >> num;之後,換行符保留在流中。然後新行將被分配到str。這就是爲什麼你認爲fflush之後的getline(正如Lundin的回答所說,fflush(stdin)是未定義的行爲)不起作用。

使用cin.ignore(A_BIG_NUM, '\n');之前getline忽略新行。