如何将枚举类型变量转换为字符串?

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.

这篇关于如何将枚举类型变量转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
Is TCHAR still relevant?(TCHAR 仍然相关吗?)
C99 stdint.h header and MS Visual Studio(C99 stdint.h 头文件和 MS Visual Studio)