我希望myprogram
接受用户输入的参数并查看每个参数是否与硬编码列表匹配。我正在寻找一个更好的替代方案来替代长 switch
语句或一系列 if else
。
这是我尝试使用enum
的一个最小示例:
$ ./myprogram blue square
//myprogram.c
#include<stdio.h>
int main(int argc, char ** argv){
//many allowable colors and shapes
enum colors_t {blue, red, /*...*/ green};
enum shape_t {square, circle, /*...*/ triangle};
//how do I check if argv[1] is on the list of colors?
if(COMPARE(argv[1], colors_t)
colors_t user_color = argv[1];
else
printf("%s is not a usable color\n",argv[1]);
//same question with shapes
if(COMPARE(argv[2], shape_t)
shape_t user_shape = argv[2];
else
printf("%s is not a usable shape\n",argv[2]);
return 0;
}
我需要使用 COMPARE()
函数来查看 argv[i]
是否与其相应的 enum
列表中的成员匹配。
最佳答案
实现此目的的一种方法是使用 qsort
和 bsearch
(好吧,如果您不介意自己对数组进行排序,则不必需要qsort)。类似于(使用您的enum color_t
):
struct color_picker {
char const *name;
enum colors_t id;
} acolor[] = { {"blue", blue}, {"red", red}, {"green", green} };
const unsigned acolor_count = sizeof acolor / sizeof acolor[0];
int cmp_color(struct color_picker const *l, struct color_picker const *r)
{
return strcmp(l->name, r->name);
}
int main(int argc, char *argv[])
{
struct color_picker *ptr;
qsort(acolor, acolor_count, sizeof acolor[0], cmp_color);
ptr = bsearch(name, acolor, acolor_count, sizeof acolor[0], cmp_color);
if (NULL == ptr) {
printf("%s is not a usable color\n",argv[1]); }
}
/* the value for `enum color_t` is in `ptr->id` */
return 0;
}
您还可以在此处使用哈希表,但 C 标准库中不支持哈希表,因此您必须自己编写代码,或使用一些第三方库。
关于将 argv[] 与允许元素列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160567/