0

I want to limit the input of the user to integer data only. So I need to validate an integer variable to an extent that it accept only integer data and not alphabetic and special character data. For example, see the code below

int a;
cout << "Enter any number: ";
cin >> a;

Now if the user enter any data other than integer type. It should give the following output without any error

Enter any number: alphabet
Invalid Input! Try again..
Enter any number:

So how do i implement it?

1 Answers1

0

The operator>> sets the stream's fail state if bad input is entered. You can test the stream's state after the read, eg:

#include <iostream>
#include <limits>

int a;
do
{
    std::cout << "Enter any number: ";
    if (std::cin >> a)
        break; // no error, a is valid
    std::cout << "Invalid Input! Try again.." << endl;
    std::cin.clear(); // reset error state
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore any pending data
}
while (true);

// use a as needed... 
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770