Daniel Daniel - 2 months ago 8
C++ Question

C++ string to enum

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

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

EDIT:

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.

Answer

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.