user2470057 user2470057 - 1 month ago 4
C Question

Check if string is valid enum in C

I am trying to figure out if there is a better way to test if a string being entered at the command line is a valid enum entry for a C program.

Is there a better way to test the entries in an enum instead of saying:

if((!strcmp(string, "NUM0")) && (!strcmp(string, "NUM1")))
{
printf("Invalid entry\n");
return(EXIT_FAILURE);
}

a3f a3f
Answer

I do it this way:

enum opt {NUM0, NUM1, NUM2, OPT_END};
static const char *opt_str[OPT_END] = {"NUM0", "NUM1", "NUM2"};

enum opt i;
for (i = 0; i < OPT_END; ++i)
   if (strcmp(string, opt_str[i]) == 0) break;

if (i == OPT_END) {
    puts("Invalid entry");
    return EXIT_FAILURE;
}
/* do something with i */

Additionally, you could employ x-macros to ensure your enums and strings are in sync: How to convert enum names to string in c.

Comments