0

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 might want to check out https://stackoverflow.com/a/57346836/2466431 – JVApen May 28 '20 at 20:40
  • You cannot. Not like that anyway. Enum's are converted to integers at compile time. Look up the std::pair class. Pairs allow you to link two types together and access the second through a pointer from the first. A common approach is linking an enum to a string. – mreff555 May 29 '20 at 00:21

1 Answers1

0

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;
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34