I would like to use an enum
value for a switch
statement. Is it possible to use the enum
values enclosed in "{}"
as choices for the switch()
"? I know that switch()
needs an int
eger value in order to direct the flow of programming to the appropriate case
number. If this is the case, do I just make a variable for each constant in the enum
statement?
I also want the user to be able to pick the choice and pass that choice to the switch()
statement.
For example:
cout << "1 - Easy, ";
cout << "2 - Medium, ";
cout << "3 - Hard: ";
enum myChoice { EASY = 1, MEDIUM = 2, HARD = 3 };
cin >> ????
switch(????)
{
case 1/EASY: // (can I just type case EASY?)
cout << "You picked easy!";
break;
case 2/MEDIUM:
cout << "You picked medium!";
break;
case 3/HARD: // ..... (same thing as case 2 except on hard.)
default:
return 0;
}
The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.
You should keep in mind that if you are accessing class-wide enum from another function even if it is a friend, you need to provide values with a class name:
Note how it is
PlayingCard::HEARTS
and not justHEARTS
.