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

标签 c string enums

我看过这个链接

How to convert enum names to string in c

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

枚举也很稀疏。

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

最佳答案

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

#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.

阅读更多 here

编辑:根据您向我们展示的具体示例,恐怕 switch-case 是您可以获得的最接近的,尤其是当您的 稀疏时枚举

关于c - 将枚举与 C 中的字符串相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10480039/

相关文章:

c - 何时使用#define 或常量 char/int?

java - 两个字符串不相等

c# - 为什么要尝试使用字符串? C# 中的(可空字符串)产生语法错误?

c# - 枚举应该以 0 还是 1 开头?

java - 代码说明: Enum and Rendering

c - 函数指针和函数名的区别

c - 使用 atoi 时出错

c - 段错误(核心转储)-此错误仅有时显示,我似乎无法修复它

c - 为什么我的数组的前一个元素会发生变化(C 中的字符串数组)

swift - 有没有办法将枚举 rawValue 向下转换为它的类型?