Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if cin is int in c++? [duplicate]

Tags:

c++

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.

like image 625
bingym Avatar asked Nov 18 '14 21:11

bingym


People also ask

How do I check if a CIN number is valid?

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.

What does Cin fail () return?

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.

What is the return type of CIN?

@anubhav Well to be clear, cin and cout cant have a return type. They are not functions.


2 Answers

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
}
like image 154
user2970916 Avatar answered Sep 24 '22 17:09

user2970916


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
}
like image 26
sedavidw Avatar answered Sep 26 '22 17:09

sedavidw