【问题标题】:Compare argv[] to list of allowable elements将 argv[] 与允许的元素列表进行比较
【发布时间】:2015-08-22 20:41:33
【问题描述】:

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

【问题讨论】:

标签: c list enums string-comparison


【解决方案1】:

一种方法是使用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 标准库中的那些,所以你必须自己编写代码,或者使用一些第三方库。

【讨论】:

  • 我没有使用您的解决方案,但我已投赞成票并标记为已接受,因为您是唯一一个可以回答的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2013-06-06
  • 2017-12-11
  • 1970-01-01
  • 2021-01-23
相关资源
最近更新 更多