How do I use an enum value in a switch statement in C++?(如何在 C++ 的 switch 语句中使用枚举值?)
问题描述
我想对 switch 语句使用 enum 值.是否可以使用 "{}" 中的 enum 值作为 switch()"的选项?
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()"?
我知道 switch() 需要一个 integer 值,以便将编程流程定向到适当的 case 编号.如果是这种情况,我是否只需为 enum 语句中的每个常量创建一个变量?
I know that switch() needs an integer 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?
我还希望用户能够选择选项并将该选项传递给 switch() 语句.
I also want the user to be able to pick the choice and pass that choice to the switch() statement.
例如:
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:
...
}
这篇关于如何在 C++ 的 switch 语句中使用枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 的 switch 语句中使用枚举值?
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
