variable with multiple types?

Is it possible to have a variable a variable, for example 'a', as both a char and an int? I ask this because I am programming a question to exit my program by either typing exit, or the number in the menu.
You can read the input as a string and then see if it contains a numerical value, what are the possible inputs?
The inputs I want are, 7 , exit and EXIT. I tried reading two difference inputs on the same line but that didn't work. I have my selections setup in a switch, where case 7 is to exit.



I'm not exactly sure where to even put the if statement :/
Last edited on
Based only on what you've posted, if the number has no numeric significance beyond identifying a menu item, then just leave it as a string/char and perform your comparison that way. So instead of evaluating the number 3, evaluate the character '3'. Then there is no difference between that and evaluating the character 'e' (or the string "3" and the string "exit").
Last edited on
char types can only contain a single character. You'd have to use a char array to contain multiple characters, but you'd be better off using STL strings for that. Easier to use, more flexible, and safer to work with as well.
Few things:
cin>>choice||wordChoice; is wrong, if you want to read two variables do cin >> choice >> wordChoice; but you need to read only one thing here
wordChoice == 'exit' strings need double quotes: "exit"
strings won't work with switch

A thing you can do is this:
- read wordChoice from cin - as a std::string as jRaskell suggested -
- check the entire string or its first character if (wordChoice[0] == '7' || wordChoice == "exit" || wordChoice == "EXIT")
- use its first character in the switch:
1
2
3
4
5
6
7
8
9
10
switch(wordChoice[0]) 	{
   case '1': // single quotes = character
       break;
   case '2':
       break;
   //........ until case 7
			
   case '7':
       break;
}

This should be the easiest way
Last edited on
Topic archived. No new replies allowed.