Home > Back-end >  How to deduce enum elements?
How to deduce enum elements?

Time:11-10

I need to write a spell book and I have two ways to do it - use enum, or use std :: map, as it is easier for me to use enum. But I ran into a problem how to display my enum?

I want to make it so that I can display all these spells on the screen and ask the user which of these spells do you want to use?

for example:

enum Book {
Tornado,
FireBall,
etc,
};

I want it to be output to the console like this :

choose one:

1.Tornado
2.FireBall

how to output this,for example with using array,is it possible?

CodePudding user response:

If you want to display the enum (Tornado, FireBall) instead of 1, 2 you can create a separate function doing that display

#include <iostream>


enum Book {
Tornado,
FireBall,
};

void yourFunction(const Book& book)
{
    switch(book)
    {
        case Book::Tornado:
            std::cout<<"Tornado"<<std::endl;
            break;
        case Book::FireBall:
            std::cout<<"FireBall"<<std::endl;
            break;
        default:
            break;
    }
}

int main()
{
    Book b=Book::FireBall;
    yourFunction(b);
    return 0;
}

CodePudding user response:

The general problem described here is associating a known integer value with a text string. The solution can be as straightforward as this:

enum Book {
    Tornado,
    Fireball,
    last_index // see below
};
static const char* names[] = {
    "Tornado",
    "Fireball"
};

To display the menu, just go through the enumerators:

for (int i = Tornado; i < last_index;   i)
    std::cout << (i   1) << '.' << names[i] << '\n';

You can do this because enumerators start at 0 and increase by 1, that is, the value of Tornado is 0 and the value of Fireball is 1. The value of last_index is 2.

The reason for using last_index is to make it easier to maintain the code. If you add an enumerator that loop doesn't change:

enum Book {
    Tornado,
    Fireball,
    GladHands,
    last_index // see below
};
static const char* names[] = {
    "Tornado",
    "Fireball",
    "Glad Hands"
};

With the added enumerator, the value of GladHands is 2 and the value of last_index is 3, so the original loop still works.

Note that this does not generate text from the name of the enumerator. The name of the enumerator has restrictions on it that the text version doesn't, so you really can't generate text in most cases. In particular, GladHands has no spaces, but its text version has one.

  • Related