Enumerative input from users

How can I get an input from a user that will place the input value into the type that I defined? For example,

enum bloodtypes = { A,B,AB,O };

How can I get an input from the user such as A,B, AB or O so that it will place the integer of the corresponding bloodtype into a variable?
Prefer enum class over regular enum.
http://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum

Perhaps something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cctype>
#include <iostream>
#include <string>

int get_bloodtype_for_str( std::string );

int main()
{
    std::string bld{};
    
    std::cout << "blood type: ";
    std::cin >> bld;
    
    std::cout << "index = " << get_bloodtype_for_str( bld ) << "\n";
}

int get_bloodtype_for_str( std::string bl )
{
    static const std::string bloodtypes_str[]{ "A", "B", "AB", "O" };
    
    for( char& c : bl ) c = toupper( c );

    for( std::size_t i{}; i < sizeof( bloodtypes_str ); i++ )
        if( bl == bloodtypes_str[i] ) return i;

    return -1;
}


blood type: a
index = 0
I'm confused by the for(char& c:bl) c = toupper(c);
I'm not familiar with this format for the for loop can you explain that?
It's a range based for-loop.
http://en.cppreference.com/w/cpp/language/range-for

It's equivalent to this:
 
for( std::size_t i{}; i < bl.size( ); i++ ) bl[i] = toupper( bl[i] );

but much easier to read.
Oh I see what you are doing here but you are getting the input from the user as a string, is it possible to get an input from the user that will accept it as an enum type that I defined?
is it possible to get an input from the user that will accept it as an enum type that I defined?

Unfortunately, enums don't support automatic translation from strings to enum values.

Taking integralfx code, we can change his get_bloodtype_for_str() function to return an enum.

1
2
3
4
5
6
7
8
9
bloodtypes get_bloodtype_for_str (string bl)
{   //  Following array MUST match the order of the enum
    static const string bloodtypes_str[] = { "A", "B", "AB", "O" };
    
    for(size_t i=0; i<sizeof(bloodtypes_str); i++)
        if (bl == bloodtypes_str[i]) 
            return (bloodtypes)i;
    return (bloodtypes)-1;  // No match found
}


Topic archived. No new replies allowed.