2013-07-03 159 views
0

我是C++新手,正在嘗試C++中的函數如何工作。輸入字符串時跳過cin?

#include <iostream> 

using namespace std; 

int add(int num, int num2){ 
    return num + num2; 
} 

int main(){ 

    int n1, n2; 
    cout << "first\t"; 
    cin >> n1; 
    cout << "second\t"; 
    cin >> n2; 

    cout << "----------\nResult\t" << add(n1, n2) << endl << endl; 

    return 0; 
} 

當我輸入兩個數字時,它很好用;但是當我輸入字符串時,它只是跳過cin >> n2行並返回6959982

first test 
second ---------- 
Result 6959982 

爲什麼會這樣呢?

+0

您應該始終檢查輸入操作的結果。 'if(std :: cin >> n1)' – chris

+0

這與「功能如何工作」有什麼關係? –

+0

@KerrekSB - 那裏有'add'功能。 –

回答

2

只是沒有閱讀。流獲取失敗位並忽略所有後續讀數。

6959982 is initial value of n2. 

您應該檢查閱讀結果。例如:

if(!(cin >> n1)) { 
    cout << "input is garbage!"; 
} 
0

http://www.parashift.com/c++-faq/istream-and-ignore.html

// Ask for a number, and if it is not a number, report invalid input. 
while ((std::cout << "Number: ") && !(std::cin >> num)) { 
    std::cout << "Invalid Input." << std::endl; 
} 

有趣數是因爲,在C++中,整數是由默認不爲0(它們可以取決於實現)。因此,無論您何時聲明一個號碼,都應將其設置爲默認值:

int x = 0; 
+1

默認情況下,它們並非真的不是0,而是它們不是0。第一種情況聽起來像是總是賦予非零值,實際上,它們未初始化,嘗試訪問值會導致未定義的行爲。 – chris

+0

在大多數實現中(如果不是全部),它會將留在該地址的值保存在內存中 – paul