Converting from String to Enum in C

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

    Warning, this is a total hack. You can use dlsym to do a lookup of a variable that is appropriately initialized. For this example to work, you have to compile to allow local symbols to be visible to the dynamic linker. With GCC, the option is -rdynamic.

    enum Day {
        SunDay, MonDay, TuesDay, WednesDay, ThursDay, FriDay, SaturDay
    };
    
    enum Day Sunday = SunDay,
             Monday = MonDay,
             Tuesday = TuesDay,
             Wednesday = WednesDay,
             Thursday = ThursDay,
             Friday = FriDay,
             Saturday = SaturDay;
    
    int main () {
        const char *daystr = "Thursday";
        void *h = dlopen(0, RTLD_NOW);
        enum Day *day = dlsym(h, daystr);
        if (day) printf("%s = %d\n", daystr, *day);
        else printf("%s not found\n", daystr);
        return 0;
    }
    

提交回复
热议问题