Casting int to enum.

Hello guys,
I have a quick question regarding enums. I have an enum called test which is made of multiple colors as shown. I want iterate using a for loop from i=0 to or from 4 to zero or whatever and I want to print the corresponding color name.
Can it be done using casting. I know I can print the corresponding number to each color what I want to do is print the color name corresponding to a certain number from 0 -4. I tried casting but I just get the integer values.

thanks
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>
using namespace std;
enum test
{
    red,
    blue,
    green,
    black,
    white,
};

int main(int argc, const char * argv[])
{
   
    for (int i=0;i<4;i++)
    {
        
        
        test castenum = (test)(i);
        cout<<castenum<<endl;
      
    }
    
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

// http://www.stroustrup.com/C++11FAQ.html#enum
enum class colour { red, blue, green, black, white, } ;

// Stream extraction and insertion in http://en.cppreference.com/w/cpp/language/operators
std::ostream& operator<< ( std::ostream& stm, colour clr )
{
    static const char* const text[] = { "red", "blue", "green", "black", "white" } ;
    return stm << "colour::" << text[ int(clr) ] ; // cast to integer
}

// http://www.stroustrup.com/C++11FAQ.html#constexpr
constexpr colour palette[] { colour::red, colour::blue, colour::green, colour::black, colour::white } ;

int main()
{
    std::cout << "the colours in the palette are:\n" ;
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( colour clr : palette ) std::cout << clr << '\n' ;
}

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