Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
58 views
in Technique[技术] by (71.8m points)

Check if character is in enum in C

Let`s say I need to read a character from the keyboard and then check if this character is valid (have some function) in the current menu part. So, if I am in firstMenu, search firstMenuKeys items, then if the character is found, call some function, otherwise throw this character. Maybe the Enum is not suitable for this purpose.

enum firstMenuKeys {

    UP = 72, 
    DOWN = 80,
    LEFT = 75, 
    RIGHT = 77,
    ENTER = 101,
    
};

enum secondMenuKeys {

    UP = 72, 
    DOWN = 80,
    ENTER = 101,
    
};




int main() {


    char c;
    c = getch();

    
    //check whether c is in firstMenuKeys


}
question from:https://stackoverflow.com/questions/65837596/check-if-character-is-in-enum-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An enum by itself is not well suited to checking a value against a set of valid values - C does not specify an operation to iterate over the enum values. One common way is to make use of an X-macro to create the enum and corresponding check function. Use of the X-macro allows the list values to be defined once and then be used in multiple contexts.

#define FIRST_MENU_KEYS 
    X(UP, 72)  
    X(DOWN, 80) 
    X(LEFT, 75)  
    X(RIGHT, 77) 
    X(ENTER, 101)

#define X(a, b) a = b,
enum firstMenuKeys {
    FIRST_MENU_KEYS
};

#define X(a, b) case a:
int isFirstMenuKey(char input)
{
    switch (input) {
        FIRST_MENU_KEYS
            return 1;
        default:
            return 0;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...