How to use enum with user input in c++

2020-06-23 06:18发布

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?!

标签: c++ enums
6条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-23 06:21

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.

查看更多
唯我独甜
3楼-- · 2020-06-23 06:22

You can do it like this:

int userInput;
std::cin >> userInput;
Throws userThrow = static_cast<Throws>(userInput);
查看更多
Emotional °昔
4楼-- · 2020-06-23 06:22

You can try this:

int userOption;
std::cin >> userOption;

If you do not want to assign user input data, just you want to check then use below code

Throws userThrow = static_cast<Throws>(userOption);

if you want to assign userinput in your Enum then use following code

Throws R = static_cast<Throws>(userOption);

here you choose R or P or S based on need.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-06-23 06:23

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 using Throws(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.

查看更多
6楼-- · 2020-06-23 06:24

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.

查看更多
狗以群分
7楼-- · 2020-06-23 06:45

Try this out:

enum Throws {R = 'R', P = 'P', S = 'S'};
char userInput;
cout << "What is your throw : ";
cin >> userInput;
Throws userThrow = (Throws)userInput;
查看更多
登录 后发表回答