简体   繁体   English

将枚举与C中的字符串相关联

[英]associating enums with strings in C

I have seen this link 我看过这个链接

How to convert enum names to string in c 如何在c中将枚举名称转换为字符串

I have a series of enums defined in the following manner in client provided library header file (which I can't change): 我在客户端提供的库头文件中以下列方式定义了一系列enums (我无法更改):

Also the enums are sparse . 枚举也很稀疏。

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

I want to print these values in my function for instance I would like to print ERROR_NONE instead of 59 . 我想在我的函数中打印这些值,例如我想打印ERROR_NONE而不是59 Is there a better way of just using switch case or if else constructs to get this done ? 是否有更好的方法只使用switch caseif else构造来完成这项工作? Example

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

A direct application of stringizing operator might be helpful 直接应用字符串化运算符可能会有所帮助

#define stringize(x) #x

printf("%s\n", stringize(ERROR_NONE));

You've mentioned that you cant change the library file. 您已经提到过您无法更改库文件。 If you decide otherwise :), you can use X macros as follows 如果你决定:),你可以使用如下的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.

Read more here 在这里阅读更多

EDIT : With the specific example you are showing us, I am afraid, switch-case is the nearest you can get, especially when you have sparse enums . 编辑 :通过你向我们展示的具体例子,我担心, switch-case是你能得到的最接近的,特别是当你有稀疏的enums

FAQ 11.17 . 常见问题11.17 Use the xstr() macro. 使用xstr()宏。 You should probably use that: 你可能应该使用它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM