2011-12-14 62 views
0

我第一次從PHP使用C++。我正在玩一些代碼。據我的理解,cin.get();是假設停止窗口關閉,直到我按下一個鍵,但它似乎沒有工作,因爲它之前的代碼,我不知道問題是什麼。這裏是我的代碼:cin.get()不工作?

#include <iostream> 
#include <cstdlib> 

using namespace std; 

int multiply (int x, int y); 

int main() 
{ 
    int x; 
    int y; 

    cout << "Please enter two integers: "; 
    cin >> x >> y; 

    int total = multiply(x, y); 
    cout << total; 

    cin.get(); 
} 

int multiply (int x, int y) { 
    return x*y; 
} 
+2

你能解釋一下你的意思嗎?「停止頁面關閉」 – 2011-12-14 05:30:29

+0

@Tyler只是使用getch();而不是cin.get(); – StackFlowed 2011-12-14 05:39:04

回答

4

將一個

cin.ignore(numeric_limits<streamsize>::max(),'\n') 

>> x >> y;後(或cin.get()之前)。

這刷新的cin緩衝區,並刪除未決\n這是仍然存在的,因爲你cin讀取x和y也讀取最後返回(Y)之後。當您致電cin.get()時,這會被讀入。如果你刷新緩衝區cin.get()將看到一個空的緩衝區,一切都很好。

1

它讀取輸入流中仍然存在的換行符,因爲上一次讀取可能會從流中提取它。

看到這個:

cin >> x >> y; 

它只讀取兩個整數,但它不會讀,當你按下按鈕能以輸入換行符。

3

您可以使用

cin.ignore(256,'\n'); 

只是最終

cin.get(); 

這會放棄之前無意 '\ n' 鍵在作爲讀取x和y的一部分。頁面從關閉停止,直到按需按下額外的按鍵。