Re: enum to string
On Sep 7, 10:36 pm, surapong <bohe...@gmail.com> wrote:
Is there any easy way to extract the string from enum variable??
e.g. I have
enum TheEnum {ONE, TWO, THREE};
I would like to generate the array of string containing
{"ONE", "TWO", "THREE"}
Thanks in advance !!
Surapong
Here is yet another way -- this one uses iostreams and locales
enum Numbers{ One,Two,Three};
struct Numbershelper:std::locale::facet{
static std::locale::id id;
Numbershelper(int refs=0): std::locale::facet(refs){
std::vector<std::string > scratch;
scratch.push_back("One");
scratch.push_back("Two");
scratch.push_back("Three");
labels.insert(label_map::value_type("C",scratch));
scratch.clear();
scratch.push_back("Ein");
scratch.push_back("Zwei");
scratch.push_back("Drei");
labels.insert(label_map::value_type("German",scratch));
scratch.clear();
scratch.push_back("Un");
scratch.push_back("Deux");
scratch.push_back("Tres");
labels.insert(label_map::value_type("French",scratch));
}
std::string get(std::string lang,Numbers idx)const{
label_map::const_iterator it=labels.find(lang);
if(it==labels.end())
it=labels.find("C");
return it->second.at(idx);
}
typedef std::map<std::string,std::vector<std::string > > label_map;
label_map labels;
};
std::locale::id Numbershelper::id;
std::ostream&operator<<(std::ostream&os, Numbers n){
std::locale loc=os.getloc();
if(std::has_facet<Numbershelper>(loc)){
Numbershelper const &h=std::use_facet<Numbershelper>(loc);
os<<h.get(loc.name(),n);
}else
os<<n;
return os;
}
int main(int ,char**)
{
std::ostringstream str;
std::locale loc(str.getloc(),new Numbershelper);
str.imbue(loc);
str<<One;
std::string label=str.str();//your string
return 0;
}
This works, except that there are no portable locale names, like I
used here. So "German" and "French" would have to be replaced with
your systems names. The "C" locale is the default for all systems.
And this is the crux of why there really isn't a standard "enum to
string" facility. Anything standardized by ISO (Like C++) has to be
internationalized, and as you can see, this can be quite a chore.
Lance