Public Group

# enum with user input

This topic is 3405 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

im reading a book beginning c++ game programing and it has a exercise to right a diffculty switch menu system using a enum for the different difficulty levels what would be the best way to do it
#include <iostream>
using namespace std;
int main()
{
enum difficulty {easy  , normal  , hard };
cout << "dfficulty levels " << endl;
cout << "1 = easy";
cout << "2 = normal";
cout << "3 = hard";
difficulty inputdef;
cin >> inputdef; // i get a error here i guess you cant use user input with enums
switch (inputdef)
{
case 0:
cout << "you picked easy" << endl;
break;
case 1:
cout << "you picked normal" << endl;
break;
case 2:
cout << "you picked hard" << endl;
break;
default:
cout << "rong" << endl;
}

}


##### Share on other sites
When you write:
enum difficulty { easy, normal, hard };
You create a new type called difficulty. The standard C++ library overloads operators << and >> for a number of built-in types and a few class templates (e.g. basic_string). However, if you want those operators to work with your own types, you have to implement the overloads yourself.

Another option is to use an anonymous enum:
enum { easy, normal, hard };
And then declare your variable as e.g.:
int inputdef;
Your code should then work as you expect (unless I overlooked something).

There are other options as well, but they might go beyond what would be appropriate for a beginning C++ programming exercise.

(Oh, and you should use the enumerants themselves in the case statements, rather than their integer values - one of the reasons for using enums is so that you can use meaningful names in your code rather than arbitrary integers.)

##### Share on other sites
The simplest solution is to just use an int to get the input from the user.

int difficultyChoice;
cin >> difficultyChoice;

Another important note is that the largest advantage of enums is largly evident in your code.

switch (difficultyChoice)
{
case 0:
cout << "You chose easy";
(...)

However a few lines about you say

cout << "1 = easy";

so the user is going to input 1 expecting easy but get normal.

to avoid this use the enum.

switch (difficultyChoice)
{
case easy:
(...)

and

cout << easy << " = easy"; // this will display '0 = easy' as it

this way no matter what easy is set to it will always display the correct number and have the correct reaction to that input from the user.

Just a side note, its good practice to initialize the first element in a enum
enum difficulty { easy = 0, normal, hard }

- Kyle

• 10
• 18
• 14
• 18
• 15