如何让 printf 显示枚举类型变量的值?例如:
How to make printf to show the values of variables which are of an enum type? For instance:
typedef enum {Linux, Apple, Windows} OS_type;
OS_type myOS = Linux;
而我需要的是类似
printenum(OS_type, "My OS is %s", myOS);
必须显示字符串Linux",而不是整数.
which must show a string "Linux", not an integer.
我想,首先我必须创建一个值索引的字符串数组.但我不知道这是否是最美丽的方式.有可能吗?
I suppose, first I have to create a value-indexed array of strings. But I don't know if that is the most beautiful way to do it. Is it possible at all?
确实没有什么漂亮的方法可以做到这一点.只需设置一个由枚举索引的字符串数组即可.
There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.
如果你做很多输出,你可以定义一个操作符<<它接受一个枚举参数并为您进行查找.
If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.
这篇关于如何将枚举类型变量转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!