【问题标题】:try catch repeating loop尝试捕获重复循环
【发布时间】:2026-02-04 21:45:01
【问题描述】:

嘿,这都是我的代码

void Student::studentMenu() {
    int choiceInput;
    const string ErrorMsg;
    cout << "-------------Student Menu--------------" << endl;
    cout << "(1)Start Quiz" << endl;
    cout << "(2)View History Score Table" << endl;
    cout << "(0)Exit" << endl;
    cout << "Option: " << endl;
    try {
        cin >> choiceInput;

        if (choiceInput < 0 || choiceInput>2 || !cin)
        {
            throw (ErrorMsg);
        }

        while (choiceInput != 0) {
            switch (choiceInput) {
            case 1:
                generateQuiz();
                break;
            case 2:
                break;
            case 0:
                break;
            }
            break;
        }
    }
    catch (string msg)
    {
        cout << "Please only enter valid integer from 0-3" << endl;
        Student::studentMenu();
    }
}

基本上,它会检查用户输入,如果输入的非整数大于 3,则抛出异常。显示错误消息后,它应该重定向回学生 menu() 页面。当我输入一个像 5 这样的整数时,输出是预期的,但是当我输入一个 char 'f' 时,它会不断循环错误消息

请帮帮我,谢谢!

【问题讨论】:

    标签: c++ exception try-catch


    【解决方案1】:
    cin >> choiceInput;
    

    当输入不是可解析的整数时会发生什么,cin 不会自动跳过它。这意味着您会陷入该值:您尝试阅读它,它失败了,您进行更深的迭代,您尝试阅读它,它失败了,等等。要解决此问题,您应该ignore 错误的字符以防万一读取失败(例如 !cin 返回 true)。通常,这看起来像这样:

    if (!cin) {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } //proceed
    

    (需要cin.clear()清除failbit,使!cin再次变为false)

    【讨论】:

      【解决方案2】:

      choiceInput 是一个整数,'f' 的 ascii 值是 102,即 > 2。我建议您应该对choiceInput 添加更多检查,以确保它是整数而不是字符。

      How to check if input is numeric in C++

      【讨论】:

      • 因为值是 102 它仍然落在像 10 这样的无效输入之外,但是为什么它会循环呢?它不会发生在 10 上。是的,我必须为此使用 try 和 exception
      【解决方案3】:

      您需要使用无效值初始化 choiceInput 变量:

      int choiceInput = -1;
      

      在你使用cout.flush() 确保在调用studentMenu() 之前清理缓冲区:

        catch (string msg)
        {
          cout << "Please only enter valid integer from 0-3: " << choiceInput << endl;
          cout.flush();
        }
      

      【讨论】: