【问题标题】:Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]如果我输入字母而不是数字,为什么会出现无限循环? [复制]
【发布时间】:2013-10-31 12:39:00
【问题描述】:

我正在为家庭作业编写此代码(刚开始 C++,所以请放轻松)。我们今天刚刚开始了 while、do-while 和 for 循环。该程序运行良好,除了如果您在程序要求整数时输入一个字母,它将无限循环。到底是怎么回事? (代码如下) ***编辑:为了澄清,循环的部分是:“您输入的数字是负数。请输入正数以继续。”但是用户没有机会输入另一个号码。它只是不断打印这个。

    #include <iostream>
using namespace std;

int main ( )
{
    //define variables
    int num1, num2, total;
    char answer1;

    do
    {
        //user enters a number
        cout << "\nPlease enter a positive number and press Enter: \n";
        cin >> num1;

        //check that the given num1 value is positive
        while (num1 < 0)
        {
            cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
            cin >> num1;
        }

        cout << endl;

        //add the sum of 1 through num1 value
        num2 = 1;
        total = 0;
        while (num1 >= num2)
        {
            total = total + num2;
            num2 ++;
        }

        //tell the user the sum
        cout << "The total of all the integers\nfrom 1 to " << num1 << " is: \n";
        cout << total;

        //ask if the user wants to try again
        cout << "\n\nWould you like to try again with a new number?\nEnter y for yes or n for no.\n";
        cin >> answer1;
    } while (answer1 == 'y');   

    cout << endl;
    return 0;
}

【问题讨论】:

  • 你错过了cin.clear()
  • 您缺少错误检查。
  • 我想我宁愿使用getline()stoi() 这样的东西,也不愿使用看似简单的流操作符。

标签: c++ infinite-loop


【解决方案1】:

这就是basic_istream 的工作原理。在您的情况下,当 cin &gt;&gt; num1 输入错误时 - failbit 已设置且 cin 未清除。所以下次它会是同样的错误输入。要正确处理此问题,您可以添加检查输入是否正确,并在输入错误的情况下清除&忽略cin。例如:

    #include<limits>

    //user enters a number
    cout << "\nPlease enter a positive number and press Enter: \n";
    do {    
        while(!(cin >> num1)) {
            cout << "Incorrect input. Please try again.\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        if(num1 < 0) cout << "The number you entered is negative. Please enter a positive number to continue.\n";
    } while(num1 < 0);

【讨论】:

  • 我们应该写什么来代替“”?
  • @AlphaMineron 没什么,streamsize 正是你写的。 std::streamsize.
【解决方案2】:

当你输入一个字母时,cin 的错误状态被设置,在你调用cin.clear() 之前不会有任何进一步的输入可能。因此,cin &gt;&gt; num1 语句不会更改 num1 的值,并且您将永远循环。

试试这个:

    while (num1 < 0)
    {
        cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
        cin.clear();
        cin >> num1;
    }

编辑:

感谢 Lightness 指出这一点。你也应该初始化num1

int num1=-1, num2, total;

【讨论】:

  • 这还不够。 num1 未初始化,因此输入字母并不能保证触发此循环。
  • 似乎确实是在 OP 的示例中触发的,但正如您所说,不能保证。谢谢。
  • 未提取触发错误的非法字符,因此您将在清除后将其作为&gt;&gt; 中的第一件事,再次设置错误。您需要以某种方式重新同步输入。
  • @LightnessRacesinOrbit 这在 C++11 中有所改变。在 C++11 之前,保证失败的 &gt;&gt;(对于数值)不会修改目标。在 C++11 中,它保证会,设置为 0 表示格式错误,+/- 最大值表示溢出。
【解决方案3】:

This answer 应该可以解决您的问题。基本上,您正在尝试从流中读取一个字符,但无法将其解析为 int,因此流处于错误状态。

你应该检查错误,清除它并做出相应的反应。

【讨论】:

  • 文本“this answer”没有说明如何解决问题。我知道这是一个链接,但如果你要参考一些额外的资源,你应该引用重要的段落。
【解决方案4】:

您可以使用“char”数据类型作为用户的输入 然后使用 "static_cast("变量名");

char input;
int choose;
cin >> input;
choose = static_cast<int>(choose) - 48;///then use 'if' statement with the variable 'choose'

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2013-05-28
    • 2020-04-02
    相关资源
    最近更新 更多