【问题标题】:why wont this do while loop exit after accepting input为什么在接受输入后循环退出时不会这样做
【发布时间】:2019-07-24 16:02:08
【问题描述】:

非常直接。我不明白为什么它在不接受 y 字符后不会退出循环。

关于 y char 和 n char,我尝试了 == 和 != 的不同变体

vector<int> v;
    char ans;
    do
    {
        cout << "Enter scores, enter number outside of 0-100 to stop:\n";
        get_scores(v);
        print_stats(v);
        cout << "Do you want to try another set of scores? Y/N: \n";
        cin >> ans;
    } while (ans != ('n' || 'N'));

在输入任何字符后,循环会不断要求更多输入。 注意:获取分数和打印统计信息功能按预期工作。

【问题讨论】:

  • @JesperJuhl 答案属于答案部分

标签: c++ visual-c++ vector while-loop


【解决方案1】:

您在 while 条件下的比较不正确,您可能打算这样做

while (ans != 'n' && ans != 'N');

('n' || 'N') 将被强制为真 (1),因此您将检查值为 1 的字符而不是 'n' / 'N'

【讨论】:

    【解决方案2】:
        } while (ans != ('n' || 'N'));
    

    在这里,您将 char 与 || 的布尔结果进行比较其他 2 个字符的操作。 这总是评估为真。 所以你的while语句是有效的

        } while (ans != true);
    

    要解决此问题,您需要将 ans 与 n 和 N 进行比较,如果其中一个为真则退出,例如:

        } while ((ans != 'n') && (ans != 'N'));
    

    【讨论】:

      【解决方案3】:

      while (ans != ('n' || 'N')) 与写 while (ans != (true)) 相同。你可能想要while ((ans != 'n') &amp;&amp; (ans != 'N'))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-31
        • 2011-02-07
        • 2013-08-31
        相关资源
        最近更新 更多