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

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

问题描述

是否有可能在 C 中将枚举器名称转换为字符串?

解决方案

一种方法,让预处理器完成工作.它还可以确保您的枚举和字符串同步.

#define FOREACH_FRUIT(FRUIT) 水果(苹果)水果(橙色)水果(葡萄)水果(香蕉)#define GENERATE_ENUM(ENUM) 枚举,#define GENERATE_STRING(STRING) #STRING,枚举 FRUIT_ENUM {FOREACH_FRUIT(GENERATE_ENUM)};静态常量字符 *FRUIT_STRING[] = {FOREACH_FRUIT(GENERATE_STRING)};

预处理器完成后,您将:

enum FRUIT_ENUM {苹果、橙子、葡萄、香蕉、};静态常量字符 *FRUIT_STRING[] = {苹果"、橙子"、葡萄"、香蕉"、};

然后你可以这样做:

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

如果用例实际上只是打印枚举名称,请添加以下宏:

#define str(x) #x#define xstr(x) str(x)

然后做:

printf("enum apple as a string: %s
", xstr(apple));

在这种情况下,两级宏似乎是多余的,但是,由于字符串化在 C 中的工作方式,在某些情况下是必要的.例如,假设我们要使用带有枚举的 #define:

#define foo 苹果int main() {printf("%s
", str(foo));printf("%s
", xstr(foo));}

输出将是:

foo苹果

这是因为 str 会将输入 foo 字符串化而不是将其扩展为 apple.通过使用 xstr,首先完成宏扩展,然后将结果字符串化.

有关详细信息,请参阅字符串化.>

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

解决方案

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

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
",FRUIT_STRING[apple]);

If the use case is literally just printing the enum name, add the following macros:

#define str(x) #x
#define xstr(x) str(x)

Then do:

printf("enum apple as a string: %s
", xstr(apple));

In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let's say we want to use a #define with an enum:

#define foo apple

int main() {
    printf("%s
", str(foo));
    printf("%s
", xstr(foo));
}

The output would be:

foo
apple

This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.

See Stringification for more information.

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

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