C++如何对开关情况进行异常处理

C++ how do I do exception handling for switch case

本文关键字:异常处理 情况 开关 C++      更新时间:2023-10-16

如果用户键入像"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>标题中。