如何在C ++中的switch语句中使用枚举值 [英] how do I use an enum value on a switch statement in C++

查看:394
本文介绍了如何在C ++中的switch语句中使用枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中使用枚举值替换我的切换。是否可以使用{}中包含的枚举值作为switch()的选择?我知道switch()需要一个整数值,以便将编程流程引导到适当的案例编号。如果是这样,我只是为'枚举'中的每个常量做一个变量?
我还希望用户能够选择并将该选择传递给switch()语句。

I would like to use an enum value for my switch statment in C++. Is it possible to use the enum values enclosed in the "{}" as choices for the "switch()"? 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' statment? 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: // ..... (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语句中使用枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆