如果用户键入像“a”这样的字母,将导致无限循环,默认值:不起作用。
我该怎么办异常处理,以便其将输出错误消息,而不是无限循环。
谢谢!
下面是我的代码:
done=false;
do
{
cout << "Please select the department: " << endl;
cout << "1. Admin " << endl;
cout << "2. HR " << endl;
cout << "3. Normal " << endl;
cout << "4. Back to Main Menu " << endl;
cout << "Selection: ";
cin >> choice;
switch (choice) {
case 1:
department_selection = "admin";
done=true;
break;
case 2:
department_selection = "hr";
done=true;
break;
case 3:
department_selection = "normal";
done=true;
break;
case 4:
selection = "hr_menu";
done=true;
break;
default:
cout << "Invalid selection - Please input 1 to 3 only.";
done=false;
}
}while(done!=true);
最佳答案
问题不是您的switch语句,而是您不检查输入操作是否真正成功的事实。始终在某些 bool(boolean) 上下文中使用输入操作:
int choice = 0;
while (!(cin >> choice) && (choice < 1 || choice > 4)) {
cout << "Invalid selection - Please input 1 to 3 only.\n";
// reset error flags
cin.clear();
// throw away garbage input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// the above two statements prevent infinite loop due to
// bad stream state
}
// proceed to switch statement
numeric_limits
模板位于<limits>
header 中。关于c++ - C++如何为开关案例进行异常处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12028203/