Home >Backend Development >C++ >How to Prevent Infinite Loops When Inputting Non-Numeric Values in C ?

How to Prevent Infinite Loops When Inputting Non-Numeric Values in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 12:45:10305browse

How to Prevent Infinite Loops When Inputting Non-Numeric Values in C  ?

Infinite Loop when Entering a Letter Instead of a Number

When encountering a character input rather than an integer, the provided code falls into an infinite loop while displaying the message "The number you entered is negative. Please enter a positive number to continue." This occurs due to the following:

Issue:

The cin stream is not properly handled when it encounters invalid input (a character in this case). It leaves the stream in an erroneous state, known as the "failbit" flag being set.

Solution:

To resolve this issue, implement the following steps:

  • Check for successful input when reading the number (using cin with the stream manipulation operator >>):

    while (!(cin >> num1)) {
        cout << "Incorrect input. Please try again.\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
  • Clear the stream and ignore the erroneous input characters if cin fails (using clear() and ignore()):

    • cin.clear() clears the "failbit" flag.
    • cin.ignore(numeric_limits::max(), 'n') removes all characters from the stream buffer up to and including the next newline character ('n').

By implementing these steps, the program will detect the invalid input, clear the stream, and prompt the user to enter a positive integer, allowing the program to continue without an infinite loop.

The above is the detailed content of How to Prevent Infinite Loops When Inputting Non-Numeric Values in C ?. 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