C ++中的切换案例无限循环错误

switch case infinite loop bug in c++

我正在开发一个菜单驱动程序来为家庭作业输出邻接矩阵。当我在调用其他 4 种情况中的任何一种后将一个字符作为我的输入时,我的循环无限运行,我无法弄清楚为什么。

无论我是否激活案例 5,都会发生这种情况。

但是如果我输入一个字符作为第一个输入,它就会按预期正常关闭。

我单步调试了调试器,似乎如果输入一个字符,它会将输入设为 4,并且不会再输入另一个,因此它会不断地打印数组。

谁能解释一下这个函数有什么问题?我只有这里的功能,因为整个程序大约有 300 行,不包括注释。但是通过一些测试,我已经将我的错误缩小到这个特定的功能,其他人按照他们的意思去做。

    void menu(char graph[][8])
{
    bool run = true;
    while (run == true)
    {
        int menuChoice;
        cout << "Welcome to the menu" << endl;
        cout << "Pick one of the following" << endl;
        cout << "1. add connection" << endl;
        cout << "2. delete connection " << endl;
        cout << "3. show total number of connections " << endl;
        cout << "4. show matrix " << endl;
        cout << " 5. to exit" << endl;
        cout << "Selection : ";
        cin >> menuChoice;
        switch (menuChoice)
        {
        case 1: addConnection(graph);
            break;
        case 2: deleteConnection(graph);
            break;
        case 3: showConnection(graph);
            break;
        case 4: showMatrix(graph);
            break;
        /*case 5:
            cout << "Exiting ...\n";
            run = false;
            break;*/
        default:
            cout << "Improper input " << endl; // for some reason this flies into infinite when a character is entered.
            cout << "Exiting ...\n";
            run = false;
            break;

        }
    }
}

这是一个教科书案例,为什么 operator>> 不应该处理交互式面向行的输入。

如果您的目的是输入一行文本,那么 std::getline() 就是为了这个。

此代码在 int.

上使用 operator>>

if a character is entered it takes that input to be 4

不,不是。 operator>> 转换失败。 menuChoice 未初始化,包含随机垃圾。它可能是'4',它可能是'X',它可能是一些不可打印的字符。天空是极限。

但更重要的是,std::cin 现在已设置失败位,任何进一步尝试从 std::cin 读取都将失败,直到流状态为 clear()ed .代码从来没有这样做,只是一遍又一遍地循环,徒劳地尝试 operator>> 下一个字符,当然,由于流处于失败状态,这不会做任何事情。由于代码不检查输入流的状态,因此它不知道发生了什么。

不要使用operator>>来阅读std::cin。如果您想阅读一行文本,请使用 std::getline(),并使用独立的 std::istringstream.

解析您阅读的任何内容