user2470057
user2470057

Reputation: 537

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);
}

Upvotes: 0

Views: 886

Answers (1)

a3f
a3f

Reputation: 8657

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.

Upvotes: 4

Related Questions