2014-12-07 61 views
2

爲了在C++中實現輸入和輸出的效果,我寫了一小段代碼。我想知道爲什麼它的行爲如此。C++:爲什麼爲「int」變量輸入「char」會導致遞歸變得瘋狂?

//A Stupid Program 
#include <iostream> 
using namespace std; 

int main() 
{ 
int x; 
cout << "please enter a numero: "; cin >> x; 
main(); 
} 

運行代碼詢問用戶「請輸入一個數字:_」,並簡單地在輸入數字時重複。這可以是任何整數。典型的輸出是這樣的:

Please enter a numero: 1 
Please enter a numero: 1 
Please enter a numero: 152 
Please enter a numero: 2 
etc... 

但是,如果輸入比int其他任何東西,遞歸循環就會發瘋,並開始打印「請輸入NUMERO:」不要求輸入。它看起來像這樣:

please enter a numero: H please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: please enter a numero: etc... 

然後程序停止工作並返回-1073741571。

所以這裏是我想要的幫助:爲什麼不輸入非int時輸入等待輸入,爲什麼它返回-1073741571?

謝謝你的幫助。

+2

根據記錄,這一計劃甚至不是有效的,因爲你不能叫'main'。鏗鏘不會編譯它。 – 2014-12-07 10:23:04

+4

在你的程序中調用'main'是非法的,因此你的問題可以簡單地用「未定義的行爲」來回答。 – 2014-12-07 10:23:06

+0

我使用Code :: Blocks,它允許調用'main'。即使在我編寫代碼時,我也明白,遞歸調用'main'是一個可怕的想法。這個程序僅僅是我的實驗的一個神器。 – Johan 2014-12-07 12:56:31

回答

3

事實上,你打電話main放在一邊(你可以只提取一切到一個單獨的函數),問題是,當你輸入一個流無法解析的東西時,它會進入一個錯誤狀態,它從每一個操作立即沒有做任何事。您需要檢查錯誤狀態並重置流以避免這種情況。

1

原因無限循環:
cin進入故障狀態,這使得它忽略它進一步呼籲,直到錯誤標誌和緩衝器復位。
爲了避免它:

int x = 0; 
    while(!(cin >> x)){ 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
     cout << "Invalid input. Try again: "; 
    } 
    cout << "You enterd: " << x << endl; 
2

試試這個:

int main() 
{ 
    while(1) 
    { 
     int x; 
     cout << "please enter a numero: "; cin >> x; 

     if (cin.fail()) 
     { 
     cout << "Please enter integer value! " << endl; 
     cin.clear(); 
     cin.ignore(INT_MAX, '\n'); 
     } 
    } 

    return 0; 
} 
相關問題