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.
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.
cin. fail() - This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state.
@anubhav Well to be clear, cin and cout cant have a return type. They are not functions.
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With