【发布时间】: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