How to return an string array from an enum in C++?

How to return an string array from an enum in C++?

Well, you can’t. You can’t just create an enumerator and then get the string. You have to create the string array for it to work.

So if you can’t do it, then what do you need to do?

I would recommend an array of strings, or a vector of strings, etc…

#include <iostream>
enum items
{
	item1 = 1, item2, item3, item4, item5
}

char * item[] = {"item1", 'item2', 'item3', 'item4', 'item5'};

int main()
{
	return 0;
}

I found this way to do this and it doesn’t seem very straight forward. It looks confusing, but hey, it works.

#define OPTIONS_LIST X(Add),\
			         X(Edit),\
					 X(New),\
					 X(Sell),\
					 X(Stock)

#define X(x) x
enum options
{
	OPTIONS_LIST
};
#undef X

#define X(x) #x
const char *szOPTIONS_LIST[] =
{
	OPTIONS_LIST
};
#undef X

There are other ways and they all seem doable but confusing to other developers. Here are some references for other confusing ways….

http://www.cplusplus.com/forum/general/2949/
Note: I liked the comment by Zaita

http://www.codeproject.com/KB/cpp/C___enums_to_strings.aspx

http://www.gamedev.net/community/forums/topic.asp?topic_id=437852

Leave a Reply

How to post code in comments?