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

时间:2015-08-22 20:41:34

标签: c list enums string-comparison

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

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是使用qsortbsearch(好吧,如果您不介意确保阵列自行排序,您不需要{ {1}})。类似的东西(使用你的qsort):

enum color_t

您也可以在此处使用哈希表,但不支持C标准库中的哈希表,因此您必须自己编写代码或使用某些第三方库。