0

I would like to prompt the user to tell me which genre the book is in. I thought I could probably give the user a menu where they enter digit for whichever choice. I wanted to know if you could just have the user input name like a string for the genre?

class Book
{
public:

    enum Genre
        {
        fiction,
        nonfiction,
        periodical,
        biograhpy,
        children
        };

    //...

    void get_genre();

    //...


private:

    //...
    Genre      genre;

};

//========================================================================================
//========================================================================================
void Book::get_genre()
{   



return;

}
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
user2904033
  • 133
  • 1
  • 3
  • 13
  • As a side note: you shouldn't use `std::cin` within your `get_genre()` method, but simply return your `genre` member there. Provide a corresponding setter method, and use `std::cin` outside the class along with the setter. – πάντα ῥεῖ Nov 18 '13 at 17:49
  • Duplicate of http://stackoverflow.com/questions/7163069/c-string-to-enum – IdeaHat Nov 18 '13 at 18:06

1 Answers1

2

You will have to map the names of the enumeration values to their values on your own. You can use a std::map<string, Genre> or std::unordered_map<string, Genre> (if c++11 is available). There is no way to convert the name of a value to its value in C++.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • You mean something like get a string from the user and then match it against Genre types in a switch or if statement? – user2904033 Nov 18 '13 at 17:47
  • @user2904033 Using the `std::map`, it's not necessary to have `if` or `switch` for mapping the values. – πάντα ῥεῖ Nov 18 '13 at 17:50
  • @user2904033 I meant a map as the solution is more dynamic and adding another value for the enumeration is easier this way. Still a switch statement is a good solution but it is harder to extend – Ivaylo Strandjev Nov 18 '13 at 17:57