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

Pie*_*ter 48 c enums printf

是否有一个单行,让我输出枚举的当前值?

bma*_*ies 46

作为一个字符串,没有.作为整数,%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]);
Run Code Online (Sandbox Code Playgroud)

这不适用于类掩码的枚举.此时,您需要一个哈希表或其他更精细的数据结构.

  • 这(当然)意味着你的枚举真正从0开始并连续没有"漏洞". (13认同)

Mat*_*ieu 23

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;
}
Run Code Online (Sandbox Code Playgroud)

你只需将枚举转换为int!
输出:我的枚举值:2

  • 枚举_are_整数. (4认同)
  • @aib,很容易忽略什么时候投,什么时候不投."enums"是什么意思?我会一直做演员.在上面,演员阵容是多余的,因为它使用的是枚举器.但如果他做了'enum MyEnum c = C_ENUM_VALUE;`然后传递`c`,他就需要演员.请参阅下面关于@ Neil答案的讨论. (4认同)

DrA*_*rAl 6

已经给出了正确答案:不,你不能给出枚举的名称,只有它的价值.

然而,只是为了好玩,这将为您提供枚举和查找表,并为您提供一种按名称打印它的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

免责声明:不要这样做.