如果我输入一个字母而不是一个数字,为​​什么我得到一个无限循环? [英] Why do I get an infinite loop if I enter a letter rather than a number?

查看:171
本文介绍了如果我输入一个字母而不是一个数字,为​​什么我得到一个无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个作业作业的代码(只是启动C ++,所以请轻松)。我们刚刚开始,do-while和for循环。该程序运行正常,除非,如果你输入一个字母,当程序要求一个整数,它无限循环。到底是怎么回事? (下面的代码)
***编辑:为了澄清,循环的部分是:您输入的数字是负数,请输入一个正数继续。但是用户没有机会输入另一个号码。

I am writing this code for a homework assignment (just starting C++ so please go easy). We've just started while, do-while, and for loops today. The program runs fine except that if you enter a letter when the program asks for an integer, it loops infinitely. What is going on? (Code below) *** To clarify, the part that is looping is: "The number you have entered is negative. Please enter a positive number to continue." But the user is not given a chance to enter another number. It just keeps printing this.

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


推荐答案

$ c> basic_istream 工程。在您的情况下, cin>> num1 获取错误的输入 - failbit 已设置, cin 未清除。所以下一次它会是同样错误的输入。要正确处理这个问题,您可以添加检查正确的输入,并清除& ignore cin ,以防输入错误。例如:

This is how basic_istream works. In your case when cin >> num1 gets wrong input - failbit is set and cin is not cleared. So next time it will be the same wrong input. To handle this correctly you can add check for correct input and clear&ignore cin in case of wrong input. For example:

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

这篇关于如果我输入一个字母而不是一个数字,为​​什么我得到一个无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆