72

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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 2
    Perhaps use `std::map` instead of enum and switch? With a bit of wrapping into an object you could make it smart enough to be reusable as an error code lookup and handler for all your apps. – AJG85 Jun 08 '11 at 15:44
  • 5
    One improvement is to omit the 'default:' clause whilst turning up the warning level on your compiler and treating warnings as errors. This way, if you ever extend the list of enums, the compiler will warn and fail on your switch statement, reminding you to extend the switch as well. Some people say you should always have a default, but I believe this is a scenario where the lack of can actually help you. – Brian O'Kennedy Jun 08 '11 at 15:46

3 Answers3

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

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
24

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

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];
Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
14

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

   return myStringMap[Enum::Apple];
nathan
  • 5,513
  • 4
  • 35
  • 47