cout Enumerations as text?

Good morning.

This is my first post and I am sure that I will be having to make a few more.

Anyway after every chapter I am learning I am trying to make my own code so I know I have grasped a certain area. So at the moment I have just finished up on Enumerations.

Here is the code I have made:

#include <iostream>
using namespace std;

int main()
{
enum difficulty {NOVICE, EASY, NORMAL, HARD, SUICIDAL};
int difficultyChoice;
cout << "Please chose a difficulty level (1-5) \nNOVICE(1), EASY(2), NORMAL(3), HARD(4), SUICIDAL(5)" << endl;
cin >> difficultyChoice;

difficulty myDifficulty;

if
(difficultyChoice == 1)
myDifficulty = NOVICE;
if
(difficultyChoice == 2)
myDifficulty = EASY;
if
(difficultyChoice == 3)
myDifficulty = NORMAL;
if
(difficultyChoice == 4)
myDifficulty = HARD;
if
(difficultyChoice == 5)
myDifficulty = SUICIDAL;


cout << "\nDifficulty Level: " << myDifficulty << endl;

cout << "\nPress the enter key to exit";
cin.ignore(std::cin.rdbuf()->in_avail() + 1);

return 0;


Now I know that each constant (NOVICE, EASY etc.) is given a value and in this case it is 0,1,2,3 and 4. So when the user chooses a difficulty level it is displaying the numeric value.

What I was wondering was is there a way to have it display the text value of NOVICE, EASY etc, or is it just written this way to make it easier for us to remember the value by name instead of number, and not actually possible to output the text value this way?

Im sure with further reading and teaching I will find a better way to do this but its only my 3rd day.

Thanks for any help it really is appreciated.

Thanks,

Dean.
An array of strings you subscript with the difficulty value.
Overload the stream insertion operator (for objects of type difficulty).

Define enum difficulty {NOVICE, EASY, NORMAL, HARD, SUICIDAL} ; outside main() and then:
std::ostream& operator<<( std::ostream& stm, difficulty d ) ;

See: http://faculty.cs.niu.edu/~mcmahon/CS241/Notes/insertion.html
Last edited on
Thanks I really appreciate your responses.

Thats a bit out of my league at the moment as my goal was to make the program on what I had learnt so far and I thought I was just missing something.

However I am still happy with the response as it means I have not failed to pick something up, just that I am not up to that point yet so thats great.

Thanks for that link I will have a read.

I think at my level (like I said Im only on day 3 so not far at all) I would have to write it like this

if
(difficultyChoice == 1)
myDifficulty = NOVICE;
cout << "\nDifficulty Level: NOVICE" << endl;
if
(difficultyChoice == 2)
myDifficulty = EASY;
cout << "\nDifficulty Level: EASY" << endl;

Its more coding but still setting the value as required.

Again Im glad for the responses and Im sure I will be needing some more insight in the future since Im teaching myself so dont have any one else to ask :)
Topic archived. No new replies allowed.