问题描述
下面就是我想要做的:
typedef enum { ONE, TWO, THREE } Numbers;
我试图写,会做类似下面的开关情况下的函数:
I am trying to write a function that would do a switch case similar to the following:
char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
而不是在所有情况下的定义,是有办法使用枚举变量就像我试图上面做设置呢?
Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?
推荐答案
有没有内置的解决方案。最简单的方法是用char *数组,其中枚举的int值索引包含枚举的描述性名称的字符串。如果你有一个稀疏的枚举(一个不从0开始或编号有差距),其中一些INT映射的是高得足以使基于阵列的映射不切实际的,那么你可以使用一个哈希表来代替。
There's no built-in solution. Easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.
这篇关于使用枚举类型的变量作为C字符串简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!