You need to define an operator>> that looks for an object of your enum:
#include <iostream>
#include <stdexcept>
using namespace std;
enum X { A, B, C };
istream& operator>> ( istream& in, X& x )
{
int val;
if ( in>> val ) {
switch ( val ) {
case A: case B: case C:
x = X(val); break;
default:
throw out_of_range ( "Invalid value for type X" );
}
}
return in;
}
int main()
{
X x;
try {
cin>> x;
cout<< x <<endl;
} catch ( out_of_range& ex ) {
cerr<< ex.what() <<endl;
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>but now when I want to display what I'm entering, I'm getting a numeric value
Well sure, what were you expecting? The very definition of an enumeration is a distinct type representing a list of named integral constants. The internal representation is basically int, so when you print the value of an enum instance, you'll get a number.
However, you can write an operator<< to print the name of the constant if you want:
#include <iostream>
#include <stdexcept>
using namespace std;
enum X { A, B, C };
istream& operator>> ( istream& in, X& x )
{
int val;
if ( in>> val ) {
switch ( val ) {
case A: case B: case C:
x = X(val); break;
default:
throw out_of_range ( "Invalid value for type X" );
}
}
return in;
}
ostream& operator<< ( ostream& out, const X& x )
{
switch ( x ) {
case A: out<<"A";
case B: out<<"B";
case C: out<<"C";
}
return out;
}
int main()
{
X x;
try {
cin>> x;
cout<< x <<endl;
} catch ( out_of_range& ex ) {
cerr<< ex.what() <<endl;
}
}
>if I was to add hand2, do I also need to create a separate operator for that?
No, the operator is overloaded for the type, so as long as hand 1 and hand2 are objects of Cards, the operator will work with them both.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401