How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
问题描述
如何让 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.
这篇关于如何将枚举类型变量转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将枚举类型变量转换为字符串?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
