简体   繁体   English

如何在c ++中使用带有用户输入的枚举

[英]How to use enum with user input in c++

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). 我的问题是我无法编译以下代码,因为从int(userInput)到Throws(userThrow)的转换无效。

enum Throws {R, P, S};
int userInput;
cout << "What is your throw : ";
cin >> userInput;
Throws userThrow = userInput;

Help?! 救命?!

You can do it like this: 你可以这样做:

int userInput;
std::cin >> userInput;
Throws userThrow = static_cast<Throws>(userInput);

R, P and S are technically now identifiers for numbers (0,1 and 2, respectively). R,P和S在技术上现在是数字的标识符(分别为0,1和2)。 Your program now does not know that that 0, 1 and 2 once mapped to letters or strings. 您的程序现在不知道0,1和2曾经映射到字母或字符串。

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. 相反,您必须接受输入并手动将其与“R”,“P”和“S”进行比较,如果匹配1,则相应地设置userThrow变量。

enums in C++ are just integer constants. C ++中的枚举只是整数常量。 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) . 基本上你从stdin读取一个int并使用它来构建一个Throws项目,使用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. 相反,如果你想通过将字符串作为输入直接输入枚举字段的表示,那么它本身就不存在,你必须手动完成,因为,如开头所述,枚举名称在编译时就消失了时间。

Try this out: 试试这个:

enum Throws {R = 'R', P = 'P', S = 'S'};
char userInput;
cout << "What is your throw : ";
cin >> userInput;
Throws userThrow = (Throws)userInput;

由于编译器将枚举视为整数,因此必须匹配手动设置每个枚举的整数以对应ASCII码,然后将整数输入强制转换为枚举。

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 如果要在Enum中分配userinput,请使用以下代码

Throws R = static_cast<Throws>(userOption);

here you choose R or P or S based on need. 在这里根据需要选择R或P或S.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM