开发者

C++ cout and enum representations

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.


This functionality comes from the IOStreams library. std::cout is an std::ostream.

std::stringstream is an std::ostream too.

int x = 5;
std::stringstream ss;
ss << x;

// ss.str() is a string containing the text "5"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜