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

标签 c++ infinite-loop

我正在为家庭作业编写此代码(刚开始使用 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;
}

最佳答案

basic_istream 就是这样工作的。在您的情况下,当 cin >> num1 输入错误时 - failbit 已设置且 cin 未清除。所以下次它会是同样的错误输入。要正确处理此问题,您可以添加检查输入是否正确,并在输入错误的情况下清除&ignore 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);

关于c++ - 如果我输入字母而不是数字,为什么会出现无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19521320/

相关文章:

c++ - 非成员(member)则不显示QLabel

java - while 循环停止检查 if 语句?

c - 寻找从 10 到 100 万的吸血鬼数字

python - 字典无限循环意外退出

c++ - 嵌套 lambda 的效率

c++ - 如何防止功能被优化

c++ - 了解 C++ 中的 clock() 和 CLOCKS_PER_SEC

mysql - 使用触发器时无限循环执行

javascript - 当我运行这段 Javascript 代码时,为什么我的浏览器总是崩溃?

c++ - Qmake 创建 Visual Studio 项目 - 设置 "Working Directory"