how to check if input is an integer?

for example, something like this

int i;

cout << "Enter integer\n";
cin >> i

how do i check if i is indeed an integer? and if it isnt, return to previous?
Read the input into a std::string object using cin.getline(). Then attempt conversion of the string to a number using a std::stringstream object. If the conversion is good, it was an integer; if not, tell the user and retry input or give up on the user.

Alternatively, and in a more simplistic way, you can probably test for cin.good(). If == true, then the input was an integer. I personally like better reading into a string first.
Last edited on
if your data type is int the what you enter is also int .
but still you want to check
1
2
3
4
5
6
7
8
if( isdigit(i) ) 
{
    stringstream strint << i ; 
string str = strint.str(); 
  if(str.find('.') == npos) 
   cout<<"congrates its integer " ; 

}
Last edited on
Topic archived. No new replies allowed.