【问题标题】:Basic input £ Indefinite looping基本输入 £ 无限循环
【发布时间】:2014-12-08 20:17:44
【问题描述】:

这是我想运行的一个非常基本的程序。要求用户在三个变体程序中进行选择,这些变体程序稍后会单独出现在代码中。

我只想接受整数输入,例如值 1、2、3、4 和 5。由于某种原因,当前程序只接受 1 输入,而对于非整数输入,while 循环会无限重复。

谁能发现这两个问题,并为我提出一些修复建议?提前致谢。

代码:

#include <iostream>

using namespace std;

int main() {
    int programversion;
    cout << "Which program version would you like to run? Basic [1], advanced [2], or advanced-variant [3]?\n";
    cin >> programversion;

    while (programversion != (1||2||3))
    {
        cout << "That is not a correct input integer - please choose [1], [2] or [3]\n";
        cin >> programversion;
    }

    if (programversion == 1)
    {
        cout << "You chose option 1.\n";
    }

    if (programversion == 2)
    {
        cout << "You chose option 2.\n";
    }

    if (programversion == 3)
    {
        cout << "You chose option 3.\n";
    }

    return 0;    
}

【问题讨论】:

  • 您的(programversion != (1||2||3)) 条件错误,但您应该通过调试代码发现。

标签: c++ loops while-loop cin indefinite


【解决方案1】:

你的情况应该是

while ( programversion < 1 || programversion > 3 )
{
    ...
}

您的while 循环继续运行的原因是因为您当前的条件总是简单地计算为真并且循环永远不会中断(除非您键入1)。 1||2||3 仅计算为 1,这是您的代码正确处理的唯一条件。如果要测试独立条件,则必须实际编写代码来单独测试这些条件。要么使用我上面的代码 sn-p(它检查 programversion 是否在 1 和 3 的范围内),要么在 while 表达式中使用多个检查来独立测试每个可接受的值。例如:

while ( programversion != 1 && programversion != 2 && ... )
{
    ...
}

【讨论】:

  • 谢谢xxbbcc!我现在知道如何更正我的代码了。
  • @Idios 很高兴这解决了您的问题。如果您不介意,请点赞并接受我的回答,如果您觉得它有用。
  • 我没有 15 声望,所以我不能投票,但是我接受了你的回答。
猜你喜欢
  • 2021-03-12
  • 2015-12-17
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 2013-07-26
  • 2012-09-27
相关资源
最近更新 更多