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;
}
We can use enums in C for multiple purposes; some of the uses of enums are: To store constant values (e.g., weekdays, months, directions, colors in a rainbow) For using flags in C. While using switch-case statements in C.
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
With the switch statement you can use int, char or, enum types. Usage of any other types generates a compile time error.
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
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With