0

I'm trying to use the (char) enum to store my ranks and then output them using cout but its not getting out correctly.

#include <iostream>

using namespace std;    

enum rank : char {
    first = '1', second = '2', third = '3'
};

int main()
{
    // other code ...
    cout << rank::third;
    // other code ...
}

It outputs 51 !!! look here - http://ideone.com/8vHzQ5

This looks like ascii values(?) so should I caste them back to char or some other type (why do I need to do so when I've already written char against that enum), otherwise what is wrong here?

apaderno
  • 28,547
  • 16
  • 75
  • 90
  • 1
    Yes, cast it back to `char`. `enum` values are `int`s, basically. Same thing as `int n='1'; std::cout << n;` – Sam Varshavchik Aug 01 '17 at 12:30
  • 1
    You can also create an overload for `std::ostream& operator<<` as seen in the example at the bottom of the reference page: http://en.cppreference.com/w/cpp/language/enum – UnholySheep Aug 01 '17 at 12:33

1 Answers1

2

By default enum values are treated as int in this case. 51 is the decimal ASCII value of 3; if you want to print 3 you need to cast it explicitly.

std::cout << static_cast<char>(rank::third);
MrPromethee
  • 721
  • 9
  • 18