Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to String C++ [duplicate]

Tags:

c++

enums

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?

like image 812
bobobobo Avatar asked Jun 08 '11 15:06

bobobobo


1 Answers

enum Enum{ Banana, Orange, Apple } ; static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };  const char * getTextForEnum( int enumVal ) {   return EnumStrings[enumVal]; } 
like image 161
Mark Ransom Avatar answered Oct 25 '22 01:10

Mark Ransom