Converting from String to Enum in C

后端 未结 6 2022
我在风中等你
我在风中等你 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:25

    That would be a good solution :

    enum e_test { a, b, c, END };
    
    enum e_test get_enum_value(char * val) {
        static char const * e_test_str[] = { "a", "b", "c" };
        for (int i = 0; i < END; ++i)
            if (!strcmp(e_test_str[i], val))
                return i;
        return END;
     }
    

提交回复
热议问题