检查字符串是否在C中是有效的枚举

时间:2016-10-30 13:42:38

标签: c string enums

我试图弄清楚是否有更好的方法来测试在命令行输入的字符串是否是C程序的有效枚举条目。

有没有更好的方法来测试枚举中的条目而不是说:

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

1 个答案:

答案 0 :(得分:4)

我是这样做的:

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 */

此外,您可以使用x-macros来确保您的枚举和字符串同步:How to convert enum names to string in c

相关问题