Converting from String to Enum in C

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

    The standard way to implement it is something along the lines of:

    typedef enum {value1, value2, value3, (...) } VALUE;
    
    const static struct {
        VALUE      val;
        const char *str;
    } conversion [] = {
        {value1, "value1"},
        {value2, "value2"},
        {value3, "value3"},
           (...)
    };
    
    VALUE
    str2enum (const char *str)
    {
         int j;
         for (j = 0;  j < sizeof (conversion) / sizeof (conversion[0]);  ++j)
             if (!strcmp (str, conversion[j].str))
                 return conversion[j].val;    
         error_message ("no such string");
    }
    

    The converse should be apparent.

提交回复
热议问题