Dennis said:
Hi this is my problem:
enum num{Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8,
Sep=9, Okt=10, Nov=11, Dec=12};
std::string month = "Dec";
num n1 = Dec; //this is working
num n2 = static_cast<num>(month); //this is not working
All i want is the number of the month as return. what to do?
Thank you Dennis
As Rolf said, there is no facilities in the C++ language
to convert from string to enum, so you will have to invent
one.
Here is an example of a Month class. This encapsulates
the enum for safety purposes:
class Month
{
public:
enum {Unknown = 0,
Jan, Feb, Mar, Apr, May, Jun,
Jul, Aug, Sep, Okt, Nov, Dec,
Maximum_Months};
Month(unsigned int new_value)
: value(new_value)
{ }
Month(char * text);
Month(const Month& m)
: value(m.value)
{ }
Month& operator=(const Month& m)
{
if (this != &m)
{
value = m.value;
}
return *this;
}
char * const to_text(void) const;
private:
unsigned int value;
const char * name_table;
};
const char * Month::names[] =
{ "Unknown",\
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
Month ::
Month(char * text)
: value(0)
{
for (unsigned int i = 0, i < Maximum_Months; ++i)
{
if (strcmp(text, names
) == 0)
{
value = i;
break;
}
}
}
char * const
Month ::
to_text(void) const
{
return names[value];
}
Other methods can be added such as:
operator<< and operator>> for streams
++, --, for incrementing and decrementing a month
+, -, for arithmetic.
to_str() for converting to a std::string
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library