Home > Backend Development > C++ > How to Convert a String to an Enum in C ?

How to Convert a String to an Enum in C ?

Mary-Kate Olsen
Release: 2024-11-11 04:13:03
Original
527 people have browsed it

How to Convert a String to an Enum in C  ?

Converting String to Enum in C

In C , there is no direct equivalent to C#'s Enum.Parse for converting strings to enums. One common solution is to use a switch statement, but for large enum lists, this approach becomes unwieldy.

Using a Map or Unordered Map

An elegant solution is to utilize a std::map or std::unordered_map to associate string keys with corresponding enum values. This allows for efficient lookup and retrieval.

std::unordered_map<std::string, MyEnum> enumMap {
    {"foo", MyEnum::Foo},
    {"bar", MyEnum::Bar}
};
Copy after login

To convert a string to an enum:

MyEnum myEnum = enumMap[myString];
Copy after login

Trivial Initialization with C 11

With C 11 and later, populating the map can be significantly simplified:

static std::unordered_map<std::string, MyEnum> const table = {
    {"a", MyEnum::a},
    {"b", MyEnum::b}
};
Copy after login

Then, to retrieve the enum value:

auto it = table.find(myString);
if (it != table.end()) {
    return it->second;
} else {
    // Handle error
}
Copy after login

The above is the detailed content of How to Convert a String to an Enum in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template