代码之家  ›  专栏  ›  技术社区  ›  Charles Ray

输入错误后while循环是否中断?

c++
  •  2
  • Charles Ray  · 技术社区  · 15 年前

    我试图让一个循环继续提示用户选择一个选项。当我得到一个字符串而不是int时,程序将无限循环。我尝试将变量结果设置为空,清除输入流,并将其包含在try catch块中(本例中没有)。有人能给我解释一下为什么会这样吗?

    #include <iostream>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    int menu(string question, vector<string> options)
    {
        int result;
    
        cout << question << endl;
    
        for(int i = 0; i < options.size(); i++)
        {
            cout << '[' << i << ']' << options[i] << endl;
        }
    
        bool ans = false;
        do
        {
            cin >> result;
            cin.ignore(1000, 10);
            if (result < options.size() )
            {
                ans = true;
            }
            else
            {
                cout << "You must enter a valid option." << endl;
                result = NULL;
                ans = false;
            }       
        }
        while(!ans);
        return result;
    }
    
    int main()
    {
        string menuQuestion = "Welcome to my game. What would you like to do?";
        vector<string> mainMenu;
        mainMenu.push_back("Play Game");
        mainMenu.push_back("Load Game");
        mainMenu.push_back("About");
        mainMenu.push_back("Exit");
    
        int result = menu(menuQuestion, mainMenu);
        cout << "You entered: " << result << endl;
        return 0;
    }
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Potatoswatter    15 年前

    看起来这里有一个随机元素,因为 result 未初始化。

    无论如何,测试 cin 直接地

        if ( cin && result < options.size() )
    

    并在无效输入时重置,以便再次执行I/O操作

            result = 0; // inappropriate to initialize an integer with NULL
            cin.clear(); // reset cin to work again
            cin.ignore(1000, '\n'); // use \n instead of ASCII code