Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string to enum

Tags:

c++

string

enums

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.

like image 302
Daniel Avatar asked Aug 23 '11 14:08

Daniel


People also ask

Can we assign string to enum?

Conclusion. In this blog post, we introduced the enum type and C# limitation of not being able to assign it a string value type.

How do you convert a string value to a specific enum type in C #?

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.

What is enum parse in C#?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.

What is size of enum in C?

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.


1 Answers

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() } 
like image 141
Mark Ransom Avatar answered Sep 30 '22 02:09

Mark Ransom