【问题标题】:Stuck in Infinite While Loop, what to do [closed]陷入无限循环,该怎么办[关闭]
【发布时间】:2015-12-08 10:34:26
【问题描述】:

这不接受任何答案:

cout << "Restart yes or no: ";
cin >> retry;
while (retry != "yes" or retry != "no"){
    cout << "Restart yes or no: ";
    cin >> retry;
    system("cls");
}

如果有人可以提供替代/修复方法,将不胜感激。

【问题讨论】:

    标签: c++ loops while-loop infinite


    【解决方案1】:

    您的代码有retry != yes or retry != no。此条件是重言式,因此总是会计算为真。

    将您的代码编辑为:

    cout << "Restart yes or no: ";
    cin >> retry;
    while (retry != "no"){
        cout << "Restart yes or no: ";
        cin >> retry;
        system("cls");
    }
    

    如果您打算循环直到收到yesno,那么while 循环应该一直运行直到输入的字符串不等于两者。您的意思是使用逻辑 AND 代替 OR。代码应为:

    while (retry != "yes" && retry != "no"){
    

    【讨论】:

    • 我喜欢你不仅指出了问题,而且还给出了逻辑规则的名称。
    【解决方案2】:

    每个字符串都不同于"yes""no"。只要字符串与 both "yes""no" 不同,您的意思就是循环 - 这意味着使用逻辑“and”运算符,而不是“or”运算符:

    while (retry != "yes" && retry != "no") {
    

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 2021-12-31
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多