Converting from String to Enum in C

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

    There isn't a direct way, but with C, you improvise. Here's an old trick. Purists may balk at this. But it's a way to manage this kind of stuff somewhat sanely. Uses some preprocessor tricks.

    In constants.h put in the following:

    CONSTANT(Sunday,  0)
    CONSTANT(Monday,  1)
    CONSTANT(Tuesday, 2)
    

    In main.c:

    #include 
    
    #define CONSTANT(name, value) \
        name = value,
    
    typedef enum {
        #include "constants.h"
    } Constants;
    
    #undef CONSTANT
    
    #define CONSTANT(name, value) \
        #name,
    
    char* constants[] = {
        #include "constants.h"
    };  
    
    Constants str2enum(char* name) {
        int ii;
        for (ii = 0; ii < sizeof(constants) / sizeof(constants[0]); ++ii) {
            if (!strcmp(name, constants[ii])) {
                return (Constants)ii;
            }   
        }   
        return (Constants)-1;
    }   
    
    int main() {
        printf("%s = %d\n", "Monday", str2enum("Monday"));
        printf("%s = %d\n", "Tuesday", str2enum("Tuesday"));
        return 0;
    }
    

    You can try other variations of the basic idea.

提交回复
热议问题