繁体   English   中英

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

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

我正在制作一个简单的石头剪刀游戏,我需要使用枚举数据结构。 我的问题是我无法编译以下代码,因为从int(userInput)到Throws(userThrow)的转换无效。

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

救命?!

你可以这样做:

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

R,P和S在技术上现在是数字的标识符(分别为0,1和2)。 您的程序现在不知道0,1和2曾经映射到字母或字符串。

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

C ++中的枚举只是整数常量。 它们在编译时被解析并变成数字。

您必须通过查找正确的枚举项来覆盖>>运算符以提供正确的转换。 我发现链接很有用。

基本上你从stdin读取一个int并使用它来构建一个Throws项目,使用Throws(val)

相反,如果你想通过将字符串作为输入直接输入枚举字段的表示,那么它本身就不存在,你必须手动完成,因为,如开头所述,枚举名称在编译时就消失了时间。

试试这个:

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

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

你可以试试这个:

int userOption;
std::cin >> userOption;

如果您不想分配用户输入数据,只需要检查然后使用下面的代码

Throws userThrow = static_cast<Throws>(userOption);

如果要在Enum中分配userinput,请使用以下代码

Throws R = static_cast<Throws>(userOption);

在这里根据需要选择R或P或S.

暂无
暂无

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

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