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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2161790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:19:26  来源:igfitidea点击:

Can I display the value of an enum with printf()?

cprintfenums

提问by Pieter

Is there a one-liner that lets me output the current value of an enum?

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

采纳答案by bmargulies

As a string, no. As an integer, %d.

作为一个字符串,不。作为整数,%d。

Unless you count:

除非你算:

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]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

这不适用于位掩码枚举之类的东西。此时,您需要一个哈希表或其他一些更复杂的数据结构。

回答by Matthieu

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;
}

You have just to cast enum to int !
Output : My enum Value : 2

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

回答by DrAl

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

已经给出了正确答案:不,您不能给出枚举的名称,只能给出它的值。

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

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

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:

枚举.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

Disclaimer: don't do this.

免责声明:不要这样做。

回答by BlueTrin

Some dude has come up with a smart preprocessor idea in this post

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

Easy way to use variables of enum types as string in C?

在 C 中使用枚举类型的变量作为字符串的简单方法?

回答by BlueTrin

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

回答by Alex Bondor

I had the same problem.

我有同样的问题。

I had to print the color of the nodes where the color was: enum col { WHITE, GRAY, BLACK };and the node: typedef struct Node { col color; };

我必须打印颜色所在节点的颜色:enum col { WHITE, GRAY, BLACK };和节点:typedef struct Node { col color; };

I tried to print node->colorwith printf("%s\n", node->color);but all I got on the screen was (null)\n.

我试图打印node->colorprintf("%s\n", node->color);但我在屏幕上看到的只有(null)\n.

The answer bmarguliesgave almost solved the problem.

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

So my final solution is:

所以我的最终解决方案是:

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