C ++ cout和枚举表示 [英] C++ cout and enum representations

查看:278
本文介绍了C ++ cout和枚举表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,我正在做一个 cout ,如: cout<当我调试时,我可以看到该值作为一个整数值,但是当 cout

$ c> spits it out,它显示为文本表示。



任何想法 cout 场景?我需要同样类型的功能,并有一些例子,将枚举值转换为字符串,但似乎我们需要知道这些值是提前的。在我的情况下,我不。我需要采取任何一个枚举,并得到其文本表示。在C#中它是一块蛋糕; C ++ ..不容易。



我可以取整数值,如果我需要并适当地转换,但字符串将给我完全需要的。 / p>

更新:



非常感谢为此问题提供帮助的所有人。最终,我发现我的答案在一些埋葬的代码。有一种方法来将枚举值转换为表示实际移动的字符串,如exd5有什么ya。在这种方法,虽然他们做一些漂亮的野生东西,我现在留在形成。我的主要目标是获得字符串表示。

解决方案

Enum.hpp:

 枚举枚举{
FOO,
BAR,
BAZ,
NUM_ENUMS
}

extern const char * enum_strings [];

Enum.cpp:

  const char * enum_strings [] = {
FOO,
BAR,
BAZ,
NUM_ENUMS,
0};

然后当我想输出枚举的符号表示时,我使用 std :: cout<< enum_strings [x]



因此,你需要知道字符串值,但只能在一个地方使用。


I have an enum that I'm doing a cout on, as in: cout << myenum.

When I debug, I can see the value as an integer value but when cout spits it out, it shows up as the text representation.

Any idea what cout is doing behind the scenes? I need that same type of functionality, and there are examples out there converting enum values to string but that seems like we need to know what those values are ahead of time. In my case, I don't. I need to take any ol' enum and get its text representation. In C# it's a piece of cake; C++.. not easy at all.

I can take the integer value if I need to and convert it appropriately, but the string would give me exactly what I need.

UPDATE:

Much thanks to everyone that contributed to this question. Ultimately, I found my answer in some buried code. There was a method to convert the enum value to a string representing the actual move like "exd5" what have ya. In this method though they were doing some pretty wild stuff which I'm staying away form at the moment. My main goal was to get to the string representation.

解决方案

Enum.hpp:

enum Enum {
  FOO,
  BAR,
  BAZ,
  NUM_ENUMS
};

extern const char* enum_strings[];

Enum.cpp:

const char* enum_strings[] = {
  "FOO",
  "BAR",
  "BAZ",
  "NUM_ENUMS",
  0 };

Then when I want to output the symbolic representation of the enum, I use std::cout << enum_strings[x].

Thus, you do need to know the string values, but only in one place—not everywhere you use this.

这篇关于C ++ cout和枚举表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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