Daniel Daniel - 5 months ago 40
C++ Question

C++ string to enum

Is there a simple way in C++ to convert a string to an enum (similar to

in C#)? A switch statement would be very long, so I was wondering if there is a simpler way to do this?


Thanks for all of your replies. I realized that there was a much simpler way to do it for my particular case. The strings always contained the charater 'S' followed by some number so i just did

int i = atoi(myStr.c_str() + 1);

and then did a switch on i.


A std::map<std::string, MyEnum> (or unordered_map) could do it easily. Populating the map would be just as tedious as the switch statement though.