如何在 C++ 中的 switch 语句上使用枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3019153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:49:01  来源:igfitidea点击:

how do I use an enum value on a switch statement in C++

c++enumsswitch-statement

提问by BotBotPgm

I would like to use an enumvalue for a switchstatement. Is it possible to use the enumvalues enclosed in "{}"as choices for the switch()"? I know that switch()needs an integer value in order to direct the flow of programming to the appropriate casenumber. If this is the case, do I just make a variable for each constant in the enumstatement? I also want the user to be able to pick the choice and pass that choice to the switch()statement.

我想enumswitch语句使用一个值。是否可以使用enum括起来的值"{}"作为“的选择switch()?我知道switch()需要一个integer 值才能将编程流程引导到适当的case数字。如果是这种情况,我是否只为每个常量创建一个变量在enum语句中?我还希望用户能够选择选项并将该选项传递给switch()语句。

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;
}

回答by Peter Ruderman

You can use an enumerated value just like an integer:

您可以像使用整数一样使用枚举值:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}

回答by Adam Holmberg

You're on the right track. You may read the user input into an integer and switchon that:

你在正确的轨道上。您可以将用户输入读入一个整数,switch然后:

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;
}

回答by radman

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.

在每个 switch 子句的末尾总是有一个中断,否则将继续向下执行到最后。

Always include the default:case in your switch.

始终将default:外壳包含在您的开关中。

Use variables of enum type to hold enum values for clarity.

为清楚起见,使用枚举类型的变量来保存枚举值。

see herefor a discussion of the correct use of enums in C++.

有关在 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
        }
    };

}

回答by AraK

You can use a std::mapto map the input to your enum:

您可以使用 astd::map将输入映射到您的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;
    }
}

回答by Aman Singh

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.

我在使用 enum 和 switch case 时遇到了类似的问题,后来我自己解决了……下面是更正的代码,也许这可能会有所帮助。

     //Menu Chooser Programe using enum
     #include<iostream>
     using namespace std;
     int main()
     {
        enum level{Novice=1, Easy, Medium, Hard};
        level diffLevel=Novice;
        int i;
        cout<<"\nenter a level: ";
        cin>>i;
        switch(i)
        {
        case Novice: cout<<"\nyou picked Novice\n"; break;
        case Easy: cout<<"\nyou picked Easy\n"; break;
        case Medium: cout<<"\nyou picked Medium\n"; break;
        case Hard: cout<<"\nyou picked Hard\n"; break;
        default: cout<<"\nwrong input!!!\n"; break;
        }
        return 0;
     }

回答by v010dya

  • Note: I do know that this doesn't answer this specific question. But it is a question that people come to via a search engine. So i'm posting this here believing it will help those users.
  • 注意:我知道这不能回答这个特定问题。但这是人们通过搜索引擎提出的问题。所以我在这里张贴这个相信它会帮助那些用户。

You should keep in mind that if you are accessing class-wide enum from another function even if it is a friend, you need to provide values with a class name:

你应该记住,如果你从另一个函数访问类范围的枚举,即使它是一个朋友,你需要提供一个类名的值:

class PlayingCard
{
private:
  enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
  int rank;
  Suit suit;
  friend std::ostream& operator<< (std::ostream& os, const PlayingCard &pc);
};

std::ostream& operator<< (std::ostream& os, const PlayingCard &pc)
{
  // output the rank ...

  switch(pc.suit)
  {
    case PlayingCard::HEARTS:
      os << 'h';
      break;
    case PlayingCard::DIAMONDS:
      os << 'd';
      break;
    case PlayingCard::CLUBS:
      os << 'c';
      break;
    case PlayingCard::SPADES:
      os << 's';
      break;
  }
  return os;
}

Note how it is PlayingCard::HEARTSand not just HEARTS.

请注意它是如何的PlayingCard::HEARTS,而不仅仅是HEARTS.

回答by bornhusker

#include <iostream>
using namespace std;

int main() {

    enum level {EASY = 1, NORMAL, HARD};

    // Present menu
    int choice;
    cout << "Choose your level:\n\n";
    cout << "1 - Easy.\n";
    cout << "2 - Normal.\n";
    cout << "3 - Hard.\n\n";
    cout << "Choice --> ";
    cin >> choice;
    cout << endl;

    switch (choice) {
    case EASY:
        cout << "You chose Easy.\n";
        break;
    case NORMAL:
        cout << "You chose Normal.\n";
        break;
    case HARD:
        cout << "You chose Hard.\n";
        break;
    default:
        cout << "Invalid choice.\n";
    }

    return 0;
}

回答by Jeremy Friesner

The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.

用户的输入将始终以字符串的形式提供给您……如果您想将用户的输入从字符串转换为整数,则需要提供代码来执行此操作。如果用户输入一个数字(例如“1”),您可以将字符串传递给 atoi() 以获取与该字符串对应的整数。如果用户输入英文字符串(例如“EASY”),那么您需要检查该字符串(例如使用 strcmp())并根据检查匹配的情况为您的变量分配适当的整数值。一旦有了从用户输入字符串派生的整数值,就可以像往常一样将其传递到 switch() 语句中。