Why does my program enter an infinite loop if the user inputs invalid data? (C++)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 2) > Why does my program enter an infinite loop if the user inputs invalid data? (C++)

This item was added on: 2003/02/20

Formatted input in C++ (by way of the >> operator) is very fickle. If you tell it you're going to enter an integer but actually enter a non-numeric string, the stream will panic and enter a failure state. The problem now is that even if you clear the error state, the bad characters that caused the panic are still in the stream, so further requests for input will just fail again.

To fix this, you test for a failure state and deal with it accordingly. In most cases, that means clearing the error state and discarding all characters left in the stream. That way you can start over with a clean slate:

#include <ios>      // For streamsize
#include <iostream>
#include <limits>   // For numeric_limits

int main()
{
  int input;

  std::cout<<"Enter a number: ";
  
  while ( !( std::cin>> input ) ) {
    // Clear the error state
    std::cin.clear();

    // Remove the unrecognized characters
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    // Try again
    std::cout<<"Invalid input. Please try again: ";
  }
  
  std::cout<<"You entered "<< input <<'\n';
}

Note: If you're unfamiliar with the funky std::numeric_limits<std::streamsize>::max() statement, it's pretty simple. Basically, it denotes the largest number of characters that the stream buffer can hold. Include <limits> to use the std::numeric_limits template. This is a similar approach to that used in the buffer flushing example.

Credit: Prelude

Script provided by SmartCGIs