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 */
4

2 回答 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是您可以获得的最接近的示例,尤其是当您有 sparse 时enums

于 2012-05-07T10:30:21.353 回答
2

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

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

 printf("%s\n", xstr(ERROR_A));
于 2012-05-07T10:26:10.010 回答