Enum to String C++ [Duplicate]

Enum to String C++ [Duplicate]

I commonly find I need to convert an enum to a string in c++

I always end up doing:

enum Enum{ Banana, Orange, Apple } ;

char * getTextForEnum( int enumVal )
{
  switch( enumVal )
  {
  case Enum::Banana:
    return "bananas & monkeys";
  case Enum::Orange:
    return "Round and orange";
  case Enum::Apple:
    return "APPLE" ;

  default:
    return "Not recognized..";
  }
}

Is there a better or recognized idiom for doing this?

2

3 Answers

enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}
10

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];
Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.