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);
}
5
  • 8
    You need to use strcmp() instead of !=. Commented Oct 30, 2016 at 13:45
  • Thank you, but that didn't answer my question. Commented Oct 30, 2016 at 13:47
  • 5
    I think it did, since your method will not work at all. Commented Oct 30, 2016 at 13:53
  • A string cannot be an enum! And how to compare strings in C has been asked a million times already! Please do at least minimal research before asking. Commented Oct 30, 2016 at 14:14
  • No, all the answers are given in C#. I did do a search... for like 3 hours. Please see the answer below. He actually read my question and answered it brilliantly. Commented Oct 30, 2016 at 16:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

That's pretty slick, thank you. The list I have is pretty big, so this will make every a lot more compact. Thanks!
@user2470057 You can use x-macros to auto-generate if the list is long.
For the sake of robustness I'd do ... char *opt_str[OPT_END] = ...
Also why not make i of type enum opt?
@alk, thanks for the suggestions. Amended the answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.