I'm at the end of chapter 2 of Michael Dawson's Beginning C++ Game Programming. The first exercise at the end of the chapter, has me rewrite a program earlier in the chapter using enumerations. The program is just a simple choose your difficulty level. You enter a number that represents the level, and it prints what level you chose. So if you enter 1, a message says you chose easy. Here is the code for that program.
// Menu Chooser
// Demonstrates the switch statement
#include <iostream>
using namespace std;
int main()
{
cout << "Difficult Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";
int choice;
cout << "Choose a difficulty level: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You chose easy.\n";
break;
case 2:
cout << "You chose medium.\n";
break;
case 3:
cout << "You chose hard.\n";
break;
default:
cout << "You made an illegal choice.\n";
}
return 0;
}
Here is the program that I have tried to rewrite using enumerations.
// Menu Chooser 2
// Menu chooser using enumerations
#include <iostream>
using namespace std;
int main()
{
cout << "Difficulty levels\n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";
enum difficulty {Easy = 1, Medium, Hard};
difficulty myDifficulty;
cout << "Please enter a difficulty level: ";
cin >> myDifficulty;
if (myDifficulty = 1)
cout << "You chose easy\n";
if (myDifficulty = 2)
cout << "You chose medium\n";
if (myDifficulty = 3)
cout << "You chose hard\n";
return 0;
}
I guess I don't fully grasp the concept of enumerations. From the explanation in the book, it seems like enumerations are a way to create your own variable type. Instead of making a variable something like "int" or "long int" or "float", you assign it to whatever you create using the enum command.
My program creates a enum called difficulty. Then I assign the variable myDifficulty as a difficulty type. The program then checks what the user inputs using the cin command and it compares it to what is allowed. Then it prints whatever difficulty level you choose.
Unfortunately, it just isn't working out that way. Perhaps someone could better explain what an enumeration is, and tell me where I went wrong using it in the program I created. Thanks in advance.