2016-02-25 60 views
0

我正在處理一個程序,該程序提示用戶通過輸入1-3的整數(4來退出)從3個不同的選項中進行選擇。我需要編寫一個驗證輸入是一個整數的代碼,如果它不是一個整數,則重新提示它們。以下是我的代碼的基本概念(完整發布時間太長)。如何在不退出我的while while循環的情況下驗證輸入?

do 
{ 
cout << "Menu: Please select one of the following options:" << endl; 
    cout << " 1 - Drop a single chip into one slot." << endl; 
    cout << " 2 - Drop multiple chips into one slot." << endl; 
    cout << " 3 - Drop 5 chips into each slot." << endl; 
    cout << " 4 - Quit the program." << endl; 
    cout << "Enter your selection now: "; 
    cin >> first_input; 
}while (first_input!=4) 

然後我有多個if語句來執行基於用戶選擇哪個選項的表達式。我還提示他們稍後在代碼中輸入其他整數值。

如果用戶輸入未能輸入整數而是輸入字符,我該如何將用戶發送回菜單?限制:不能使用continuebreak

在此先感謝。

回答

0

您在尋找continue的關鍵字。

+0

感謝您快速回復。有另一種方法嗎?雖然我肯定會解決它,但我不需要使用「繼續」。 – Alectris

+0

@ T.Rydalch:什麼或誰要求?如果你有任意的限制條件,你可以「允許」使用C++,如果你在下次問題中預先說明問題,而不是等到我們已經寫了答案,我會很感激。 ... –

+0

正式注意。我的課程導師。 – Alectris

0
do 
{ 
    cout << "Menu: Please select one of the following options:" << endl; 
    cout << " 1 - Drop a single chip into one slot." << endl; 
    cout << " 2 - Drop multiple chips into one slot." << endl; 
    cout << " 3 - Drop 5 chips into each slot." << endl; 
    cout << " 4 - Quit the program." << endl; 
    cout << "Enter your selection now: "; 
    cin >> first_input; 
    //lets say if user enters value out of range. then want to show menu again. 
    if(first_input > 4) { 
     cout << "Invalid input "<<endl; 
     continue; 
    } 
    // you can do other stuff here. 
    // ... 
}while (first_input!=4) 
+0

這不解決OP的問題「*如果用戶輸入未能輸入整數而是輸入字符,我該如何將用戶發送回菜單?」 – NoseKnowsAll

1

如果你想回到非整數輸入的情況下的開始,也許這樣的事情會工作?

// Insert after "cin >> first_input;" 
if (cin.fail()) { 
    // Handle non-int value. 

    // Clear error flag. 
    cin.clear(); 

    // Empty buffer up to next newline. 
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

    // Complain & restart. 
    cout << "Invalid input. Please try again." << endl; 
    continue; 
} 

這樣做是清除錯誤標誌,清除緩衝區,並返回到開始。 cin.ignore()不明確需要通過std::numeric_limits<std::streamsize>::max()作爲其第一個參數;但是,如果出現錯誤,我寧願這樣做以確保錯誤的輸入消失。請注意,std::numeric_limits是在標準報頭<limits>中定義的,並且要求包含它。

+0

謝謝!非常感謝您的幫助。 – Alectris

+0

@Alectris不客氣。 –

0

您可以嘗試使用轉到標籤。

do{ 
    label: 
     // your code 
if(check) goto label; 
}while(check);