How do I use an enum value in a switch statement in C++?
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: // ..... (the same thing as case 2 except on hard.)
default:
return 0;
}
You can use an enumerated value just like an integer:
myChoice c;
...
switch( c ) {
case EASY:
DoStuff();
break;
case MEDIUM:
...
}
You're on the right track. You may read the user input into an integer and switch
on that:
enum Choice
{
EASY = 1,
MEDIUM = 2,
HARD = 3
};
int i = -1;
// ...<present the user with a menu>...
cin >> i;
switch(i)
{
case EASY:
cout << "Easy\n";
break;
case MEDIUM:
cout << "Medium\n";
break;
case HARD:
cout << "Hard\n";
break;
default:
cout << "Invalid Selection\n";
break;
}
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.
namespace choices
{
enum myChoice
{
EASY = 1 ,
MEDIUM = 2,
HARD = 3
};
}
int main(int c, char** argv)
{
choices::myChoice enumVar;
cin >> enumVar;
switch (enumVar)
{
case choices::EASY:
{
// do stuff
break;
}
case choices::MEDIUM:
{
// do stuff
break;
}
default:
{
// is likely to be an error
}
};
}
You can use a std::map
to map the input to your enum
:
#include <iostream>
#include <string>
#include <map>
using namespace std;
enum level {easy, medium, hard};
map<string, level> levels;
void register_levels()
{
levels["easy"] = easy;
levels["medium"] = medium;
levels["hard"] = hard;
}
int main()
{
register_levels();
string input;
cin >> input;
switch( levels[input] )
{
case easy:
cout << "easy!"; break;
case medium:
cout << "medium!"; break;
case hard:
cout << "hard!"; break;
}
}