C++如何对开关情况进行异常处理
C++ how do I do exception handling for switch case
如果用户键入像"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 语句,而在于您没有检查输入操作是否真的成功。始终在某些布尔上下文中使用输入操作:
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>
标题中。
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C++如何对开关情况进行异常处理
- 在低内存情况下使用带有异常处理的STL容器