C++ cout and enum representations

那年仲夏 提交于 2019-12-24 01:51:10

问题


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.


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/6169315/c-cout-and-enum-representations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!