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.
Conclusion. In this blog post, we introduced the enum type and C# limitation of not being able to assign it a string value type.
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.
The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.
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.
Edit: Since C++11, populating is trivial:
static std::unordered_map<std::string,E> const table = { {"a",E::a}, {"b",E::b} }; auto it = table.find(str); if (it != table.end()) { return it->second; } else { error() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With