如果输入字母而不是数字,为什么会出现无限循环?

时间:2013-10-22 14:53:54

标签: c++ infinite-loop

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

    #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;
}

4 个答案:

答案 0 :(得分:13)

这就是basic_istream的工作原理。如果cin >> 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);

答案 1 :(得分:1)

当您输入字母时,cin的错误状态已设置,并且在您致电cin.clear()之前无法再进行任何输入。因此,语句cin >> 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;

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

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

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