如何枚举类型变量转换为字符串?
问题描述:
如何使的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 what 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.
如果你做大量的输出,你可以定义一个运营商的LT;<这需要一个枚举参数,并执行查找适合你。
If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.