if (variable != integer)

Hello. I need to have an if statement that says that if a variable is not an integer, do something, and else (if it is) do something else. How can I do this? Any help would be appreciated. Thank you!
Maybe there could be an array or a string entered instead of an int and if it doesn't have 0,1,2,3,4,5,6,7,8,9 there could be an error message or something but I am unsure of the code to do that with strings or arrays.
C++ is statically typed... which means a variable is whatever type you determine it is... and it cannot be changed.

IE:

1
2
3
4
5
6
7
int foo;

// foo is ALWAYS an integer... no matter what.

string bar;

// bar is ALWAYS a string... no matter what. 



So what you're asking doesn't really make sense.



What you probably want... is you want to know if the user input an integer or not. In which case you can check the error state of cin:

1
2
3
4
5
6
7
8
9
10
11
12
13
int foo;  // foo is always an int
cin >> foo;  // try to get an int from the user

// if they didn't give you an int... 'cin' goes into a bad state:
if( !cin )
{
    // user did not input an integer
}
else
{
    // user input an integer
    //  it is contained in 'foo'
}




EDIT:

Also... when cin goes into a bad state... you'll have to put it back into a "good" state before attempting to read any more data:

1
2
cin.clear();  // clear error state
cin.ignore(9999,"\n"); // throw away buffered data (it was bad) 
Last edited on
Thank you very much! That worked. I am curious though, what exactly does !cin mean?
!<insert variable> means if the variable is equal to zero.
But in this case (with if (!cin)), it checks whether cin is in an error state.
!cin invokes the istream::operator !, which is documented here:
http://www.cplusplus.com/reference/ios/ios/operator_not/

Basically... it's the same as doing this:
cin.fail()
(also documented here:
http://www.cplusplus.com/reference/ios/ios/fail/ )

Which checks to see if the stream is in a bad state.
Topic archived. No new replies allowed.