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;
}
You're on the right track. You may read the user input into an integer and
switch
on that:Some things to note:
You should always declare your enum inside a namespace as enums are not proper namespaces and you will be tempted to use them like one.
Always have a break at the end of each switch clause execution will continue downwards to the end otherwise.
Always include the
default:
case in your switch.Use variables of enum type to hold enum values for clarity.
see here for a discussion of the correct use of enums in C++.
This is what you want to do.
You can use a
std::map
to map the input to yourenum
:You can use an enumerated value just like an integer:
i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.