在C语言中将枚举与字符串关联

在C语言中将枚举与字符串关联,c,string,enums,C,String,Enums,我看到了这个链接 我在客户端提供的库头文件中以以下方式定义了一系列enum(我无法更改): 枚举也是稀疏的 typedef enum { ERROR_NONE=59, ERROR_A=65, ERROR_B=67 } 我想在函数中打印这些值,例如,我想打印ERROR\u NONE而不是59。是否有更好的方法只使用开关大小写或if-else结构来完成此操作? 范例 int Status=0; /* some processing in librar

我看到了这个链接

我在客户端提供的库头文件中以以下方式定义了一系列
enum
(我无法更改):

枚举也是稀疏的

typedef enum
{
    ERROR_NONE=59,   
    ERROR_A=65,  
    ERROR_B=67
}
我想在函数中打印这些值,例如,我想打印
ERROR\u NONE
而不是
59
。是否有更好的方法只使用
开关
大小写
if-else
结构来完成此操作? 范例

   int Status=0;
   /* some processing in library where Status changes to 59 */
   printf("Status = %d\n",Status); /* want to print ERROR_NONE instead of 59 */
。使用
xstr()
宏。您可能应该使用:

 #define str(x) #x
 #define xstr(x) str(x)

 printf("%s\n", xstr(ERROR_A));

直接应用字符串化运算符可能会有所帮助

#define stringize(x) #x

printf("%s\n", stringize(ERROR_NONE));
您已经提到无法更改库文件。如果您另有决定:),则可以按如下方式使用
X

enumstring.c
#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)

#define C(x) x,

enum color { NAMES TOP };

#undef C

#define C(x) #x,

const char * const color_name[] = { NAMES };

int main( void ) 
{ printf( "The color is %s.\n", color_name[ RED ]);  
  printf( "There are %d colors.\n", TOP ); }

stdout
The color is RED. 
There are 3 colors.
enumstring.c
#包括
#定义名称C(红色)C(绿色)C(蓝色)
#定义C(x)x,
枚举颜色{NAMES TOP};
#未定义C
#定义C(x)#x,
const char*const color_name[]={NAMES};
内部主(空)
{printf(“颜色为%s.\n”,颜色名称[红色]);
printf(“有%d种颜色。\n”,顶部);}
stdout
颜色是红色的。
有三种颜色。
阅读更多


编辑:就您向我们展示的具体示例而言,
开关箱
恐怕是最接近的,尤其是当您有稀疏的
枚举

时,为什么不使用?你能给我们看一些你试图打印这些枚举值的代码吗?你需要一个两步宏来强制扩展和字符串化。看见