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

5

我看到了这个链接

如何将枚举名称转换为C++字符串

我在客户提供的库头文件中以以下方式定义了一系列enums(我不能更改):

此外,这些枚举是稀疏的。

typedef enum
{
    ERROR_NONE=59,   
    ERROR_A=65,  
    ERROR_B=67
}

我希望在我的函数中打印这些值,例如我想打印 ERROR_NONE 而不是 59。是否有更好的方法仅使用 switch caseif 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 */

为什么不使用字符串化运算符?您能展示一些打印枚举值的代码吗? - Pavan Manjunath
2个回答

3
一个直接应用字符串化操作符的例子可能会有所帮助。
#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.

点击这里了解更多信息。

编辑: 根据您提供的具体示例,我担心在您有稀疏枚举时,switch-case是最接近的选择。


你需要一个两步宏来强制执行扩展和字符串化。请参见http://c-faq.com/ansi/stringize.html。 - dirkgently

2

常见问题解答 11.17。使用xstr()宏。你应该使用它:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接