8

Possible Duplicate:
Easy way to use variables of enum types as string in C?

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

A simplified example of calling a function that takes an 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

Community
  • 1
  • 1
squater
  • 189
  • 1
  • 2
  • 8
  • 1
    I think you meant `strcmp` instead of `strcpy` ? – cnicutar Dec 27 '11 at 09:26
  • 1
    @bobbymcr it is not a dupe; this question is similar but it is the other way around (string to enum inst of enum to string). –  Dec 27 '11 at 09:46
  • [Easy way to use variables of enum types as string in C?](http://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c) is used to get the name of the ENUM, using the ENUM value as an input. I'm needing to get the ENUM value using the ENUM name as the input. – squater Dec 27 '11 at 09:50
  • @cnicutar yes sorry, modified the question to reflect that – squater Dec 27 '11 at 09:54

2 Answers2

17
$ 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

is my favorite way to do such things. This ensures that no consistency errors can occur between the enum and the mapping array.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 3
    +1 for a simple solution. For a more generic solution that hides the unreadable macro stuff to the application programmer see http://p99.gforge.inria.fr/p99-html/group__types.html – Jens Gustedt Dec 27 '11 at 09:49
4

No, there is no other way; because an enum is, inside the machine, just some number. You could use some preprocessor tricks. See this question.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547