如果我有这个代码:
enum {
blue,
red,
//...
}
main(){
char * color;
color = (char * )malloc.....
getString(&color);
// Now let say color = "red"
printf("%d",function_to_search_enums_by_name_and_returing_them(color));
// '1' will be printed
}
有没有(不是复杂的)方法来实现这个目标?
if
' s / switch
,并且只涵盖enum
的所有选项。
什么"更好"那呢?答案 0 :(得分:2)
实现这一目标的一种方法是
#include <stdio.h>
#define FOREACH_COLOR(FUNC) \
FUNC(BLUE) \
FUNC(RED) \
/* ... */
#define GENERATE_ENUM(val) val,
#define GENERATE_STRING(val) #val,
int main(int argc, char **argv) {
enum colors {
FOREACH_COLOR(GENERATE_ENUM)
};
const char *color_strings[] = {
FOREACH_COLOR(GENERATE_STRING)
};
printf("Key: %d, String: %s", BLUE, color_strings[BLUE]);
/*
* Output will be:
* Key: 0, String: BLUE
*/
return (0);
}
要获取给定字符串的枚举值,请在color_strings
中执行查找并返回枚举值(不测试该代码):
int get_enum_value_from_string(const char **color_strings, const size_t strings_cnt,
const char *color) {
int i;
for (i = 0; i < strings_cnt; ++i) { /* for each color */
if (strcmp(color, color_strings[i]) == 0) {
/* if the given string matches an entry in the color array */
return (i); /* this is the droid we're looking for! */
}
}
return (-1); /* not found */
}
答案 1 :(得分:1)
set
答案 2 :(得分:-1)
如果您正在编写纯C,并希望使用字符串作为相应枚举的键,则必须使用一组&#34;如果&#34;&#34;来自&#34; string.h&#34;
的 strcmp如果您可以使用C ++,我建议您使用 std :: map 和一对&#34; std :: string&#34;和&#34; int&#34;。您可以将字符串用作键,结果将比任何C方法更清晰。
编辑:如果你愿意,你也可以使用你的枚举作为地图的第二个元素