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

发布于 2024-09-05 14:19:20 字数 805 浏览 1 评论 0原文

我想在 switch 语句中使用 enum 值。是否可以使用 "{}" 中包含的 enum 值作为 switch()" 的选择?

我知道 switch() 需要一个 integer 值,以便将编程流程引导到适当的 case 编号。如果是这种情况,我是否只需执行此操作即可。 enum 语句中的每个常量都有一个变量?

我还希望用户能够选择选项并将该选项传递给 switch() 语句,

例如:

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

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 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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

想你的星星会说话 2024-09-12 14:19:22

您可以将 enum 与 int 进行转换。

enum TYPE { one, two, tree };

TYPE u;

u = two;

switch( int( u ) ){
        case one : 
        action = do_something ;
        break;
        case two:
        action = do_something_else;
        break;
}

You can cast enum with int.

enum TYPE { one, two, tree };

TYPE u;

u = two;

switch( int( u ) ){
        case one : 
        action = do_something ;
        break;
        case two:
        action = do_something_else;
        break;
}
无敌元气妹 2024-09-12 14:19:21

您可以使用 std::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;
    }
}

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;
    }
}
豆芽 2024-09-12 14:19:21

我在使用带有开关盒的枚举时遇到了类似的问题。

后来我自己解决了......下面是更正后的代码,也许这可能会有所帮助。

//Menu Chooser Programme 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;
}

I had a similar issue using enum with switch cases.

Later, I resolved it on my own....below is the corrected code, and perhaps this might help.

//Menu Chooser Programme 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;
}
樱花落人离去 2024-09-12 14:19:21

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

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

注意它是如何PlayingCard::HEARTS 而不仅仅是HEARTS

You should keep in mind that if you are accessing a 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::HEARTS and not just HEARTS.

忘东忘西忘不掉你 2024-09-12 14:19:21

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

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.

世态炎凉 2024-09-12 14:19:21
#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;
}
#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;
}
没有心的人 2024-09-12 14:19:20

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

myChoice c;

...

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

You can use an enumerated value just like an integer:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}
燃情 2024-09-12 14:19:20

你走在正确的轨道上。您可以将用户输入读取为整数并对其进行切换

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

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;
}
审判长 2024-09-12 14:19:20

需要注意的一些事情:

您应该始终在名称空间内声明枚举,因为枚举不是正确的名称空间,您会很想像使用它们一样使用它们。

始终在每个 switch 子句的末尾有一个中断,否则执行将继续向下直到结束。

始终在开关中包含 default: 大小写。

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

有关 C++ 中枚举的正确使用的讨论,请参阅此处

这就是您想要做的。

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

}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文