enum class cast?

Jul 16, 2014 at 6:51pm
I am trying to set the value of an enum class type object with the value given by the user from the command prompt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

enum class EnergyState : unsigned char {
    ON,
    OFF
};

int main()
{
    EnergyState state;
    unsigned char s;
    std::cin >> s;
    state = static_cast<EnergyState>(s);    // Something goes wrong here?
    std::cout << static_cast<unsigned char>(state) << std::endl;    // Test
    std::cout << "Your computer is currently "
              << ((state == EnergyState::ON) ? "on" : "off")
              << "." << std::endl;
    return 0;
}


Is this type of assignment (state = static_cast<EnergyState>(s);) possible, or do I have to do something like this instead?

1
2
3
4
5
std::cin >> s;
if (s == 0)
    state = EnergyState::ON;
else if (s == 1)
    state = EnergyState::OFF;
Last edited on Jul 16, 2014 at 6:55pm
Jul 16, 2014 at 6:55pm
EnergyState::On should be equal to 0 and off equal to 1. I would change state = static_cast<EnergyState>(s); to state = s or just simply remove the state part then at the end put ((s == EnergyState::ON) ? "on" : "off")

Sorry it should just be static_cast<EnergyState>(s-'0'); didn't realize you are using unsigned char instead of int.
Last edited on Jul 16, 2014 at 6:58pm
Jul 16, 2014 at 7:37pm
The problem was the use of unsigned char? I don't understand why there is a difference using unsigned short int for instance. Both unsigned char and unsigned short int are integral types.

The following seems to work just fine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

enum class EnergyState : unsigned short int {
    ON,
    SUSPENDED,
    OFF
};

int main()
{
    EnergyState state;
    unsigned short int s;
    std::cin >> s;
    state = static_cast<EnergyState>(s);
    std::cout << "Your computer is currently "
        << ((state == EnergyState::ON) ? "on" : (state == EnergyState::SUSPENDED) ? "suspended" : "off")
        << "." << std::endl;
    return 0;
}
Jul 16, 2014 at 7:48pm
When its a char it reads it in as '0' which is 48 in the ascii table and when you read in as an int it reads in as 0.
Jul 16, 2014 at 8:42pm
Of course. How simple. Yet another one of those moments when I feel stupid and enlightened at the same time. Thank you.
Topic archived. No new replies allowed.