问题描述
有没有采取一个字符串(由用户输入),并将其转换为枚举值convienent的方式?在这种情况下,该字符串将枚举值的名称,例如:
Is there a convienent way to take a string (input by user) and convert it to an Enumeration value? In this case, the string would be the name of the enumeration value, like so:
enum Day
{
Sunday = 0,
Monday = 1,
...
}
因此,如果用户给一个日的名称,就能够解析为相应的枚举值
So that if the user gave the name of a Day, it would be able to parse that to the corresponding Enum value.
诀窍是,我有超过500个值我的工作,他们正穿过多个枚举$ P $垫出来。
The trick is, I have over 500 values I'm working with, and they are spread out across multiple enumerations.
我知道在C#中Enum.Parse方法,所以有在C某种形式的吗?
I know of the Enum.Parse Method in c#, so is there some form of this in c?
推荐答案
要实现它的标准方式是沿着线的东西:
The standard way to implement it is something along the lines of:
typedef enum {value1, value2, value3, (...) } VALUE;
const static struct {
VALUE val;
const char *str;
} conversion [] = {
{value1, "value1"},
{value2, "value2"},
{value3, "value3"},
(...)
};
VALUE
str2enum (const char *str)
{
int j;
for (j = 0; j < sizeof (conversion) / sizeof (conversion[0]); ++j)
if (!strcmp (str, conversion[j].str))
return conversion[j].val;
error_message ("no such string");
}
相反的应该是显而易见的。
The converse should be apparent.
这篇关于从字符串转换为枚举用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!