0

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);
}
user2470057
  • 529
  • 4
  • 17

1 Answers1

4

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.

Community
  • 1
  • 1
a3f
  • 8,517
  • 1
  • 41
  • 46
  • That's pretty slick, thank you. The list I have is pretty big, so this will make every a lot more compact. Thanks! – user2470057 Oct 30 '16 at 13:54
  • 3
    @user2470057 You can use [x-macros](https://en.wikipedia.org/wiki/X_Macro) to auto-generate if the list is long. – P.P Oct 30 '16 at 13:55
  • 1
    For the sake of robustness I'd do `... char *opt_str[OPT_END] = ...` – alk Oct 30 '16 at 14:49
  • Also why not make `i` of type `enum opt`? – alk Oct 30 '16 at 14:51
  • @alk, thanks for the suggestions. Amended the answer. – a3f Oct 30 '16 at 15:57
  • @user2470057 You're welcome. If your question is answered, please show so by marking an answer as accepted. – a3f Oct 30 '16 at 15:58
  • I was going to earlier, but they have a timer set on it. I guess they want to make sure other people get a chance to answer. Anyway, yes, answer accepted. I totally love the way you implemented this whole thing. – user2470057 Oct 30 '16 at 16:15