如何枚举名称转换为字符串在C [英] How to convert enum names to string in c

查看:184
本文介绍了如何枚举名称转换为字符串在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有枚举名称转换为字符串在C可能性?

Is there a possibility to convert enumerator names to string in C?

推荐答案

另一种方式,使得preprocessor做的工作。它还确保您的枚举和字符串是同步的。

Another way, making the preprocessor do the work. It also ensures your enums and strings are in sync.

#define FOREACH_FRUIT(FRUIT) \
        FRUIT(apple)   \
        FRUIT(orange)  \
        FRUIT(grape)   \
        FRUIT(banana)  \

#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,

enum FRUIT_ENUM {
    FOREACH_FRUIT(GENERATE_ENUM)
};

static const char *FRUIT_STRING[] = {
    FOREACH_FRUIT(GENERATE_STRING)
};

在preprocessor得到执行后,您将有:

After the preprocessor gets done, you'll have:

enum FRUIT_ENUM {
    apple, orange, grape, banana,
};

static const char *FRUIT_STRING[] = {
    "apple", "orange", "grape", "banana",
};

然后,你可以这样做:

Then you could do something like:

printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);

另一种方式,如果用例是真的只是打印枚举名称:

Another way, if the use case is literally just printing the enum name:

#define str(x) #x

然后执行:

printf("enum apple as a string: %s\n", str(apple));

这篇关于如何枚举名称转换为字符串在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆