1

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

1 回答 1

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>标题中。

于 2012-08-19T16:53:00.083 回答