C: ENUM Map String

Possible duplicate:
An easy way to use enum type variables as a string in C?

Is there any elegant way to convert a user's input string to an ENUM value is direct C, besides the manual way.

A simplified example of calling a function that takes ENUM as an argument:

enum = {MONDAY,TUESDAY,WEDNESDAY}; ... //Get user to enter a day of the week from command line ... //Set the work day according to user input if (strcmp(user_input,"MONDAY")==0){ SET_WORK_DAY(MONDAY); } else if (strcmp(user_input,"TUESDAY")==0){ SET_WORK_DAY(TUESDAY); } ... 

thanks

+7
source share
2 answers
 $ cat wd.c #include <stdio.h> #define mklist(f) \ f(MONDAY) f(TUESDAY) f(WEDNESDAY) #define f_enum(x) x, #define f_arr(x) {x, #x}, enum weekdays { mklist(f_enum) WD_NUM }; struct { enum weekdays wd; char * str; } wdarr[] = { mklist(f_arr) }; int main(int argc, char* argv[]) { int i; for (i=0; i < sizeof(wdarr)/sizeof(wdarr[0]); i++) { if (strcmp(argv[1], wdarr[i].str) == 0) { printf("%d %s\n", wdarr[i].wd, wdarr[i].str); return 0; } } printf("not found\n"); return 1; } $ make wd cc wd.c -o wd $ ./wd MONDAY 0 MONDAY $ ./wd TUESDAY 1 TUESDAY $ ./wd FOODAY not found 

- my favorite way to do such things. This ensures that there is no matching error between the enum and the display array.

+16
source

No, there is no other way; because enum only has a certain number inside the machine. You can use some preprocessing tricks. See this question .

+4
source

All Articles