Ghazanfar Ali
Ghazanfar Ali

Reputation: 123

How to get next value of enum

I have the following problem:

    enum Language { English, French, German, Italian, Spanish };

    int main() {

    Language tongue = German;
    tongue = static_cast<Language>(tongue + 1);

      cout << tongue;                  

}

//it returns 3.....but i want to get the language name on index 3.....

Upvotes: 3

Views: 9064

Answers (4)

Thomas Matthews
Thomas Matthews

Reputation: 57678

I find that an explicit look up table works best, for both converting from enum to text and text to enum:

enum Language_Enum
{
    LANGUAGE_FIRST = 0,
    LANGUAGE_GERMAN = LANGUAGE_FIRST,
    LANGUAGE_ENGLISH,
    LANGUAGE_HOPI,
    LANGUAGE_WELSH,
    LANGUAGE_TEXAN,
    LANGUAGE_DUTCH,
    LANGUAGE_LAST
};

struct Language_Entry
{
    Language_Enum   id;
    const char *    text;
};

const Language Entry  language_table[] =
{
    {LANGUAGE_GERMAN, "German"},
    {LANGUAGE_HOPI, "Hopi"},
    {LANGUAGE_DUTCH, "Dutch"},
    // ...
};
const unsigned int language_table_size =
    sizeof(language_table) / sizeof(language_table[0]);

Specifying the enum along with the text, allows for the enum order to change with minimal effect to the search engine.

The LANGUAGE_FIRST and LANGUAGE_LAST identifiers allow for iteration of the enum:

Language_Enum l;
for (l = LANGUAGE_FIRST; l < LANGUAGE_LAST; ++l)
{
    // ...
}

Upvotes: 3

Cyrus1
Cyrus1

Reputation: 226

Best Way to use enum is first give initial value to your enum. enum TestEnum { Zero=0, One, Two } Even you wont specify anything the default starting index is zero. To get the value at a particular index simple do that

TestEnum(index);

Upvotes: 0

Component 10
Component 10

Reputation: 10487

You'll have to create an array of strings which matches your enum e.g.

std::string[] LangTxt = { "English", "French", "German", "Italian", "Spanish" };

then you can reference them as follows:

cout << LangTxt[tongue];

Be careful to keep the definitions together though so they are updated side by side.

Upvotes: 3

Sjoerd
Sjoerd

Reputation: 75588

It is not so simple to print the enum name for a given enum value in C++. Instead, you can use a map or string array to hold the values, which do allow you to get both the index and the string value.

Upvotes: 2

Related Questions