I declared a enum type as this,
enum WeekEnum { Mon = 0; Tue = 1; Wed = 2; Thu = 3; Fri = 4; Sat = 5; Sun = 6; };
How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."
I already have a function as this
Log(Today is "2", enjoy! );
And now I want the output below
Today is Wed, enjoy
Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
You can use: int i = Convert. ToInt32(e); int i = (int)(object)e; int i = (int)Enum. Parse(e.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
You can't directly, enum
in C++ are not like Java enums.
The usual approach is to create a std::map<WeekEnum,std::string>
.
std::map<WeekEnum,std::string> m; m[Mon] = "Monday"; //... m[Sun] = "Sunday";
Here is another neat trick to define enum using X Macro:
#include <iostream> #define WEEK_DAYS \ X(MON, "Monday", true) \ X(TUE, "Tuesday", true) \ X(WED, "Wednesday", true) \ X(THU, "Thursday", true) \ X(FRI, "Friday", true) \ X(SAT, "Saturday", false) \ X(SUN, "Sunday", false) #define X(day, name, workday) day, enum WeekDay : size_t { WEEK_DAYS }; #undef X #define X(day, name, workday) name, char const *weekday_name[] = { WEEK_DAYS }; #undef X #define X(day, name, workday) workday, bool weekday_workday[] { WEEK_DAYS }; #undef X int main() { std::cout << "Enum value: " << WeekDay::THU << std::endl; std::cout << "Name string: " << weekday_name[WeekDay::THU] << std::endl; std::cout << std::boolalpha << "Work day: " << weekday_workday[WeekDay::THU] << std::endl; WeekDay wd = SUN; std::cout << "Enum value: " << wd << std::endl; std::cout << "Name string: " << weekday_name[wd] << std::endl; std::cout << std::boolalpha << "Work day: " << weekday_workday[wd] << std::endl; return 0; }
Live Demo: https://ideone.com/bPAVTM
Outputs:
Enum value: 3 Name string: Thursday Work day: true Enum value: 6 Name string: Sunday Work day: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With