Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]

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) ***EDIT: 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;
}
like image 416
user2907563 Avatar asked Oct 22 '13 14:10

user2907563


People also ask

How do I stop the Infinity loop?

You can press Ctrl + C .

What causes an infinite loop in coding?

Usually, an infinite loop results from a programming error - for example, where the conditions for exit are incorrectly written. Intentional uses for infinite loops include programs that are supposed to run continuously, such as product demo s or in programming for embedded system s.

Why is my for loop running infinitely?

This is a silly example, but it's common for infinite loops to accidentally occur. Most of the times, it's because the variables used in the condition are not being updated correctly, or because the looping condition is in error. We print out x, y, and z since these variables appear in the condition.

What causes an infinite loop in C++?

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty.


1 Answers

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);
like image 79
Sergey Avatar answered Sep 26 '22 03:09

Sergey