Enumerations

How do I get the actual value from an enum instead of just a number?
What do you mean by "actual value"??

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

enum {A = 'a', B, C, D, E};

int main() {
	cout << B << endl;
	cout << static_cast<char>(B) << endl;
	return 0;
}
Last edited on
The value you assign instead of just a number to represent it.
I believe that is what I have shown above, you can cast it to the desired type in order to see the value assigned to the enumerated type.

The output of the above code is:
98
b
Do you mean something like
1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    enum myEnum {SOMETHING, SOMETHING_ELSE, BLAH};
    
    myEnum m = BLAH;
    std::cout << /* something involving 'm' */; // Prints "BLAH"
}
?

I'm pretty sure that's not possible, or at least not directly.
Yeah, that's what I mean. If there's no way to do it then thanks to both of you for your help.
You might be able to fake it using a std::vector (if your enums have their default values) or std::map (if you've assigned custom values for your enums):
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <vector>

int main()
{
    enum myEnum {SOMETHING, SOMETHING_ELSE, BLAH};
    std::vector<std::string> enumStrings = {"SOMETHING", "SOMETHING_ELSE", "BLAH"};

    myEnum m = BLAH;
    std::cout << enumStrings[m]; // Prints "BLAH"
}
Something like this (the example uses a scoped enum; treatment would be identical for unscoped enums):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <stdexcept>

enum class colour { WHITE, GREY, BLACK } ;

std::string to_string( colour clr )
{
    switch(clr)
    {
        case colour::WHITE: return "colour::WHITE" ;
        case colour::GREY: return "colour::GREY" ;
        case colour::BLACK: return "colour::BLACK" ;
    }

    throw std::domain_error( "uninitialized colour" ) ;
}

std::ostream& operator<< ( std::ostream& stm, colour clr )
{ return stm << to_string(clr) ; }

int main()
{
     const auto clr_cloud = colour::GREY ;
     std::cout << clr_cloud << '\n' ;
}

http://coliru.stacked-crooked.com/a/84b0407f9e227fb2
Topic archived. No new replies allowed.