Iman Fakhari
Iman Fakhari

Reputation: 85

how to give index of an enum value an get it?

i have this enum:

enum Status { CONTINUE, WON, LOST };

i want to give index of one the values (e.g 1 for WON) and get the value (WON). i searched but i just find the opposite method!!! i found this code to do but it gives me the index again:

int main()
{
enum Status { CONTINUE, WON, LOST };
int myInteger = 1;
Status myValue = (Status)myInteger;
cout << myValue <<endl;//it rerurns 1 !!!
system("PAUSE");
}

so what id the syntax of getting a value from an enum?? //i need something like array[1]

Upvotes: 0

Views: 1921

Answers (3)

Papulatus
Papulatus

Reputation: 677

enum type just saves the value not the name

may be you could code like this

enum Status { CONTINUE, WON, LOST };
const char* status_names[] = {"CONTINUE", "WON", "LOST"};
int myInteger = 1;
cout << status_names[myInteger] << endl; 

here is the ideone link

Upvotes: 1

Raydel Miranda
Raydel Miranda

Reputation: 14360

You can use map from the STL.

for instace:

#include <iostream>
#include <map>
#include <string> 


using namespace std;

int main()
{

    typedef enum { CONTINUE, WON, LOST } status_t;

    map<int, string> Status = {
        {CONTINUE, "CONTINUE"},
        {WON, "WON"},
        {LOST, "LOST"}
    };


    cout << Status[1] << endl;    
    // It's also possible
    cout << Status[CONTINUE] << endl;    



    return 0;
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490098

C++ "inherited" enum from C. It's really little more than a short-hand notation for the traditional way of doing things in C, where your enum would have been something like:

#define CONTINUE 0
#define WON 1
#define LOST 2

enum automates assigning successive numbers to the symbols, but not much more than that.

C++11 added enum class that creates an enumeration that's more like a normal type, but it still doesn't provide an (automated) way to convert from a numeric representation to the symbol you used.

Upvotes: 3

Related Questions