将 argv[] 与允许元素列表进行比较

Compare argv[] to list of allowable elements

我希望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 列表中的成员相匹配。

一种方法是使用 qsortbsearch(好吧,如果您不介意自己对数组进行排序,则不需要 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 标准库中不支持这些,所以你必须自己编写代码,或者使用一些第三方库。