![](/img/trans.png)
[英]What is wrong with getchar (as program is exiting without a check at do while loop)?
[英]How do I validate input without exiting my do while loop?
我正在開發一個程序,該程序通過輸入1-3(退出4)來提示用戶從3個不同的選項中進行選擇。 我需要編寫一個代碼來驗證輸入是否為整數,如果不是整數則重新提示它們。 這是我的代碼的基本思想(整個發布太久了)。
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語句根據用戶選擇的選項執行表達式。 我還將提示他們稍后在代碼中輸入其他整數值。
如果用戶輸入未能輸入整數而是輸入字符,如何將用戶送回菜單? 約束:不能使用continue
或break
提前致謝。
如果您想重新開始使用非整數輸入,也許像這樣的事情行得通嗎?
// 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>
定義的,並且需要將其包括在內。
您正在尋找continue
關鍵字。
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)
您可以嘗試使用goto標簽。
do{ label: // your code if(check) goto label; }while(check);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.