C ++如何对switch case进行异常处理

时间:2012-08-19 16:46:05

标签: c++

如果用户键入字母“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);

1 个答案:

答案 0 :(得分:3)

问题不在于您的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>标题中。