Rhyous

December 7, 2009

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

Filed under: C/C++ — J. Abram barneck @ 8:43 pm

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

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: