首页 文章

while循环对非整数响应奇怪

提问于
浏览
1

因此,在运行此测试时我遇到问题,以确保while循环正常工作 . 如果为cin << a输入非整数值;如果输入的是一个整数而不是列出的其中一个,那么循环将无休止地执行而不需要a的其他值,但是我希望它能解释用户尝试的任何输入 . 有没有一种简单的方法来解决这个问题?我假设它与一个int有关,但我稍后需要一个int作为switch语句 .

int a;
cout << "What type of game do you wish to  play?\n(Enter the number of the menu option for)\n(1):PVP\n(2):PvE\n(3):EVE\n";
cin >> a;
while (!((a == 1) || (a == 2) || (a == 3)))
{
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n";
    a = 0;
    cin >> a;
}

2 回答

  • 4
    cin >> a;
    

    如果此代码失败(如果您提供非整数数据,则会执行此操作),流将进入无效状态,并且对 cin >> a 的所有后续调用将立即返回,没有副作用,仍处于错误状态 .

    这是一个我不太喜欢的C设计决策(也可能是为什么大多数人不喜欢C中的Streams设计),因为你希望这会引发错误或者之后恢复正常,就像大多数其他语言一样 . 相反,它无声地失败,这是许多程序错误的最大来源 .

    无论如何,有两个可能的解决方案 .

    第一种是正确检查流是否仍然有效 . 像这样:

    while (!((a == 1) || (a == 2) || (a == 3)))
    {
        cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n";
        a = 0;
        if(!(cin >> a)) break; //Input was invalid; breaking out of the loop.
    }
    

    如果输入无效,这将中断循环,但会使流处于无效状态 .

    另一种方法是将流重置为有效状态 .

    while (!((a == 1) || (a == 2) || (a == 3)))
    {
        cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n";
        a = 0;
        while(!(cin >> a)) {
            std::cin.clear();
            std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
            std::cout << "Please only enter Integers." << std::endl;
        }
    }
    

    第二种通常是人们需要的方法,但可能存在第一种更有意义的情况 .

  • 0

    我得到了它的工作:

    int a;
    cout << "What type of game do you wish to  play?\n(Enter the number of the menu option for)\n(1):Player V Player\n(2):Player vComp\n(3):Comp V Comp\n";
    cin >> a;
    while (a != 1 && a != 2 && a != 3 || cin.fail())
    {
        cout << "That is not a valid gametype. Pick from the following menu:\n(1):Player V Player\n(2):Player vComp\n(3):Comp V Comp\n";
        cin.clear();
        cin.ignore(256, '\n');
        cin >> a;
    }
    

相关问题