I am trying to write an if statement but cannot find the proper expression form to use. I’m thinking of writing something like this:
if ( var != type(int) )
However, I am unsure exactly how to go about doing this, and this method does not work.
Am I at least thinking along the right lines?
It sounds like you’re trying to overload a function:
If you want
int-special behavior and then something else in all other cases, you can use templates:According to your comment (“Task at hand is a simple program: Take two user inputted integers and add them. Restrict input to integer only. I can do it in Python and I am thinking too along those lines. if num1 != type(int): print “You did not enter an integer, please enter a integer.” else: continue”), you want something like this:
This will notify invalid input such as “@#$”, “r13”, but does not catch cases such as “34fg”, “12$#%”, because it will read the
int, and stop at “fg” and “$#%”, respectively.To check that, you will have to read in a line of input, and then try to convert that line into the type you want. (Thanks, litb). That means your question is more like this question:
This does the following: get input, and put it into a
stringstream. Then after parsing theint, stream out any remaining white space. After that, ifeofis false, this means there are left-over characters; the input was invalid.This is much easier to use wrapped in a function. In the other question, the cast was re-factored away; in this question we’re using the cast, but wrapping the input along with it.
Or more generically:
This let’s you parse other types with error checking.
If you’re okay with exceptions, using
lexical_cast(either from boost, or “faked”, see the other question linked in-code [same as above link]), your code would look something like this:I don’t think boost has a no-throw version of lexical cast, so we can make a true/false rather than exception version of this code by catching
bad_cast‘s, as follows. Once again, this works with eitherboostor a custom lexical cast. (Anything that does a lexical cast and throwsbad_cast):Now it’s back to a
boolresult, except we avoid code duplication by using existinglexical_castfunctions.You can of course choose which method you would like to use.