5

I'm writing a program that only accepts int for user input at this point, if its not, keep asking user until get the right integer. Here is the code below:

cout << "enter two integers: " << endl;
string input1, input2;
cin >> input1;
cin >> input2;

while (//if they are not integers)
...//ask again

As you can see, I use string to store the input, but I don't know how to check this string contains only an integer number.

bingym
  • 53
  • 1
  • 1
  • 4

2 Answers2

12

cin will toggle it's failbit if the user does not enter a correct data type that it was expecting. Changing the datatype of the inputs to int and checking this failbit will allow you to validate user input.

#include <limits> // This is important!

cout << "enter two integers: " << endl;
int input1, input2;
std::cin >> input1;
std::cin >> input2;

while (!std::cin.good())
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    ...//ask again
}
Sean Bone
  • 3,368
  • 7
  • 31
  • 47
user2970916
  • 1,146
  • 3
  • 15
  • 37
4

You shouldn't use string at all.

int input1, input2;
cin >> input1;

Then you can check if cin failed

if (!cin) {
     // input was not an integer ask again
}
sedavidw
  • 11,116
  • 13
  • 61
  • 95