简体   繁体   中英

Retrive Values From Enum

How can i recieve a specific value from an enum from a given index.


enum genre { Pop, Jazz, Classic}; //enum
struct album
{

    string album_name;
    genre kind;
    int track_number;
    string tracks[5];
    string tracklocation;
};

void main()
{
    album x1;
    cout<<"Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    cin>>temp;
    x1.kind=(genre)temp;   // typecasting for int to enum
    cout<<x1.kind<<endl;
}

When i run this code i just get the integer value i input, instead of the converted enum value

what i need is when user input 0,1 or 2 it needs to be converted using the enum to the relevant genre and saved in the stucture variable.

You can't put the identifiers (names) of an enum to cout . For example, the value of the name Pi in enum , suppose it's set to 3.14 . You directly wants the user would type that value, it'll show the string Pi in output stream, but no, it's only within supposed within the code. Enumeration just holds the constants.

By default, your declaration enum {Pop, Jazz, Classic} holds the constant values 0, 1 and 2 respectively.

Rather, you could use arrayed string to get a value. Consider the following example:

struct album {
    string album_name;
    string genre[3] = {"Pop", "Jazz", "Classic"}; // this one holds 0 = "Pop" ...
    int track_number;
    string tracks[5];
    string tracklocation;
};

And the driver code:

int main(void) {
    album x1;
    int temp;

    std::cout << "Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    std::cin >> temp;

    std::cout << x1.genre[temp] << endl;
    // will display 0 = "Pop", 1 = "Jazz", 2 = "Classic"

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM