Converting from String to Enum in C

后端 未结 6 2028
我在风中等你
我在风中等你 2020-12-05 15:42

Is there a convienent way to take a string (input by user) and convert it to an Enumeration value? In this case, the string would be the name of the enumeration value, like

6条回答
  •  感动是毒
    2020-12-05 16:28

    If you're using straight C, there isnt a "Enum.Parse" equivalent. You'll want to write your own function, comparing the user's string to pre-defined values with strcmp(), and then returning the appropriate enum value.

    Another possibility is using an existing "hash map" implementation, or rolling your own - for instance, the one in glib should work for you: https://developer.gnome.org/glib/2.30/glib-Hash-Tables.html

    A hash map should be faster than doing a linear search on the possible enum values, if you have a lot of them (for instance, if you were doing something other than the days of the week). A good hash map implementation should be close to O(1) for lookups, instead of O(n) for a linear search.

提交回复
热议问题