Home >Backend Development >C++ >Why Does My C Program Enter an Infinite Loop with Non-Numeric Input?

Why Does My C Program Enter an Infinite Loop with Non-Numeric Input?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 10:18:11181browse

Why Does My C   Program Enter an Infinite Loop with Non-Numeric Input?

Why Does the Program Loop Endlessly When Inputting a Letter Instead of a Number?

When attempting to input a positive integer in a C program but accidentally entering a letter instead, an infinite loop may occur. This behavior stems from how the input stream cin processes characters.

When input is incorrect (e.g., a letter instead of a number), the cin stream sets the failbit flag and leaves the incorrect input in the buffer. Subsequent attempts to read an integer using cin will continue to return the incorrect input, resulting in an endless loop.

To resolve this issue, it's crucial to handle incorrect input properly by checking for errors and clearing the input buffer. Here's a modified version of the code that includes error handling:

#include <iostream>
#include <limits>

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

    do
    {
        // User enters a number
        cout << "\nPlease enter a positive number and press Enter: ";
        while (!(cin >> num1))
        {
            cout << "Incorrect input. Please try again." << endl;
            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." << endl;
    } while (num1 < 0);

    // Rest of the code goes here

    return 0;
}

In this updated code, the while (!(cin >> num1)) loop runs until a valid integer is entered. When an incorrect input is detected, an error message is displayed, and the input buffer is cleared using cin.clear() and cin.ignore(). This ensures that the program can continue reading input correctly after handling the error.

The above is the detailed content of Why Does My C Program Enter an Infinite Loop with Non-Numeric Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn