If/else using differing data types?

Okay, so my question for today is is it possible to make a program that would have something like an if/else statement, but have the if/else use different data types.

For example:
The program asks a user for a number to perform a specific operation, this number can be any number they want.

If (user inputs a number)
run the program how you want it to.
else (ideally the user would enter the string 'exit')
return 0;

Is there a way I can have an if/else statement do this? Or some other way?
closed account (N36fSL3A)
Look up operator overloading.
Each 'if' statement in an else/if chain has its own condition. You can use whatever variables of whatever type in the 2nd condition ... it doesn't matter what type of variables were used in the first condition.

But that's kind of a non-question... and I don't think it's the answer you're looking for. I suspect you are asking if you can do something like this:

1
2
3
4
5
6
7
8
9
int foo;
cin >> foo;
if( foo_is_an_int )
{
}
else
{
  // foo is not an int
}


The answer to that is "no, not with ints". An int is always going to be an int.. even if the user does not input an integer. If they do not, the cin>>foo line will simply fail and 'foo' will not have anything meaningful.

Instead, if you want to catch any and all input data, you'll have to read it as a string:

1
2
3
4
5
6
7
8
9
10
11
string foo;
cin >> foo;

if( doesStringContainNumericalData( foo ) )
{
  //...
}
else
{
  // user input something that was not numerical
}


This you certainly CAN do.


EDIT:

@Lumpkin: I don't see what operator overloading has to do with this. And even if it was relevant, your answer is extremely vague as operator overloading is a pretty broad topic and this was a pretty specific question.
Last edited on
Topic archived. No new replies allowed.