Im making a simple rock paper scissors game and I need to use the enumeration data structure. My problem is that i cannot compile the following code because of an invalid conversion from int (userInput) to Throws (userThrow).
enum Throws {R, P, S};
int userInput;
cout << "What is your throw : ";
cin >> userInput;
Throws userThrow = userInput;
Help?!
R, P and S are technically now identifiers for numbers (0,1 and 2, respectively). Your program now does not know that that 0, 1 and 2 once mapped to letters or strings.
Instead, you must take the input and manually compare it to "R", "P" and "S" and if it matches one, set the
userThrow
variable accordingly.You can do it like this:
You can try this:
If you do not want to assign user input data, just you want to check then use below code
if you want to assign userinput in your Enum then use following code
here you choose R or P or S based on need.
enums in C++ are just integer constants. They are resolved at compile time and turned into numbers.
You have to override the
>>
operator to provide a correct conversion by looking for the correct enum item. I found this link useful.Basically you read an int from stdin and use it to build a
Throws
item by usingThrows(val)
.If, instead, you want to input directly the representation of the enum field by placing as input the string then it doesn't exist by itself, you have to do it manually because, as stated at the beginning, enum names just disappear at compile time.
Since enumerations are treated as integers by the compiler, you must match manually set the integer for each enum to correspond to the ASCII code, then cast the integer input to your enumeration.
Try this out: