我可以用printf()显示一个枚举的值吗?

有没有让我输出枚举的当前值的单线程?

作为一个string,不。 作为整数,%d。

除非你数:

static char* enumStrings[] = { /* filler 0's to get to the first value, */ "enum0", "enum1", /* filler for hole in the middle: ,0 */ "enum2", "enum3", .... }; ... printf("The value is %s\n", enumStrings[thevalue]); 

这不适用于像掩码的枚举类似的东西。 在这一点上,你需要一个哈希表或其他更复杂的数据结构。

 enum MyEnum { A_ENUM_VALUE=0, B_ENUM_VALUE, C_ENUM_VALUE }; int main() { printf("My enum Value : %d\n", (int)C_ENUM_VALUE); return 0; } 

你只需要枚举int!
输出: 我的枚举值:2

已经给出了正确的答案:不,你不能给一个枚举的名字,只有它的价值。

不过,只是为了好玩,这会给你一个enum和一个lookup-table在一个给你的手段打印它的名字:

main.c中:

 #include "Enum.h" CreateEnum( EnumerationName, ENUMValue1, ENUMValue2, ENUMValue3); int main(void) { int i; EnumerationName EnumInstance = ENUMValue1; /* Prints "ENUMValue1" */ PrintEnumValue(EnumerationName, EnumInstance); /* Prints: * ENUMValue1 * ENUMValue2 * ENUMValue3 */ for (i=0;i<3;i++) { PrintEnumValue(EnumerationName, i); } return 0; } 

Enum.h:

 #include <stdio.h> #include <string.h> #ifdef NDEBUG #define CreateEnum(name,...) \ typedef enum \ { \ __VA_ARGS__ \ } name; #define PrintEnumValue(name,value) #else #define CreateEnum(name,...) \ typedef enum \ { \ __VA_ARGS__ \ } name; \ const char Lookup##name[] = \ #__VA_ARGS__; #define PrintEnumValue(name, value) print_enum_value(Lookup##name, value) void print_enum_value(const char *lookup, int value); #endif 

Enum.c

 #include "Enum.h" #ifndef NDEBUG void print_enum_value(const char *lookup, int value) { char *lookup_copy; int lookup_length; char *pch; lookup_length = strlen(lookup); lookup_copy = malloc((1+lookup_length)*sizeof(char)); strcpy(lookup_copy, lookup); pch = strtok(lookup_copy," ,"); while (pch != NULL) { if (value == 0) { printf("%s\n",pch); break; } else { pch = strtok(NULL, " ,.-"); value--; } } free(lookup_copy); } #endif 

免责声明:不要这样做。

有些老兄在这篇文章中提出了一个聪明的预处理器的想法

在C中使用枚举types的variables作为string的简单方法?

 enum A { foo, bar } a; a = foo; printf( "%d", a ); // see comments below 

我有同样的问题。

我不得不打印颜色的节点的颜色: enum col { WHITE, GRAY, BLACK }; 和节点: typedef struct Node { col color; }; typedef struct Node { col color; };

我尝试用printf("%s\n", node->color);打印node->color printf("%s\n", node->color); 但是我在屏幕上显示的是(null)\n

bmargulies给出的答案几乎解决了这个问题。

所以我最终的解决scheme是:

 static char *enumStrings[] = {"WHITE", "GRAY", "BLACK"}; printf("%s\n", enumStrings(node->color));