How to overload istream operator while using enums?

I'm familiar with how to overload operators using classes, but I'm having some trouble when it comes to using enums as I have never used them before. The program is meant to get rid of any sort of menu and overload the istream and ostream operators and print the suit of the user's card only if it is a valid suit. I'm currently only getting 0 when printing enumVar, I would like to print the number in place of the user's suit so long as it is a valid choice. Here is my code:

#include <iostream>
#include <string>
#include <type_traits>

using namespace std;

enum suits {hearts, diamonds, clubs, spades};

template<typename T>

typename std::enable_if<std::is_enum<T>::value, std::istream&>::type
operator >>(std::istream &is, T& enumVar)
{
std::cout << "\n\nenum\n";
int intVal;
is >> intVal;
enumVar = static_cast<T>(intVal);
std::cout << enumVar;

return is;
}

int main()
{
suits card;

cout << "\n\nEnter the suit of your card: ";
cin >> card;

return 0;
}
Something like this, perhaps:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <cctype>

enum suit_t { HEART, DIAMOND, CLUB, SPADE } ;
static const std::string suit_symbol = "HDCS" ;

std::ostream& operator<< ( std::ostream& stm, suit_t suit )
{ return stm << suit_symbol[suit] ; }

std::istream& operator>> ( std::istream& stm, suit_t& suit )
{
    char c ;
    if( stm >> c )
    {
        const std::size_t pos = suit_symbol.find( std::toupper(c) ) ;
        if( pos != std::string::npos ) suit = suit_t(pos) ;
        else stm.setstate( stm.failbit ) ; // invalid input, put the stream into a failed state
    }
    return stm ;
}

suit_t get_suit()
{
    suit_t suit ;
    std::cout << "enter suit (one of " << suit_symbol << "): " ;

    // fine if a single character representing a valid suit was entered
    if( std::cin >> suit && std::isspace( std::cin.peek() ) ) return suit ;

    else
    {
        std::cout << "invalid input. try again\n" ;
        std::cin.clear() ; // clear the failed state
        std::cin.ignore( 1000, '\n' ) ; // discard the rest of the input line
        return get_suit() ; // try again
    }
}

int main()
{
    const suit_t suit = get_suit() ;
    std::cout << "suit: " << suit << '\n' ;
}
Topic archived. No new replies allowed.