cin to an enum

How do I overload the >> operator to cin to a type enum?
same as for any other user-defined type, define std::istream& operator>>(std::istream&, Enum&)
What is the implementation of that function?
What do you want the user to enter? A string or a number? The whole point of enums is that the number they are shouldn't matter.

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
27
28
29
30
31
32
33
34
35
// Example program
#include <iostream>
#include <string>

enum Animal {
  Cat = 1,
  Dog = 2,
  Pig = 3
};


std::istream& operator>>(std::istream& is, Animal& animal)
{
    int a;
    is >> a;
    animal = static_cast<Animal>(a);

    return is;
}

int main()
{
    Animal animal;
    std::cin >> animal;

    switch (animal)
    {
      case Pig:
          std::cout << "Pigs are the most equal animal." << std::endl;
          break;
      default:
          std::cout << "Only pigs are allowed to be chosen, sorry!" << std::endl;
          break;
    }
}
If you have an enum like
1
2
3
4
5
enum Sample{
    First,
    Second,
    Third,
};
and you want to read from the input words like "First", you'll have to do the parsing manually. Unfortunately C++ doesn't have reflection.
Otherwise you can go with something simple like
1
2
3
int val;
if (stream >> val)
    dst = (Sample)val;
If you want the input to be a string, you have to do something like this. As helios said, C++ doesn't have reflection, so you have to manually make the connection between string "Dog" and enum Dog.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Example program
#include <iostream>
#include <string>

enum Animal {
  Cat,
  Dog,
  Pig
};

std::istream& operator>>(std::istream& is, Animal& animal)
{
    std::string name;
    is >> name;

    if (name == "Cat")
        animal = Cat;
    else if (name == "Dog")
        animal = Dog;
    else if (name == "Pig")
        animal = Pig;

    return is;
}


int main()
{
    Animal animal;
    std::cin >> animal;

    switch (animal)
    {
      case Pig:
          std::cout << "Pigs are the most equal animal." << std::endl;
          break;
      default:
          std::cout << "Only pigs are allowed to be chosen, sorry!" << std::endl;
          break;
    }
}


edit: fixed code
Last edited on
Great thank you all!
Topic archived. No new replies allowed.