4

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

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

帮助?!

4

6 回答 6

7

你可以这样做:

int userInput;
std::cin >> userInput;
Throws userThrow = static_cast<Throws>(userInput);
于 2016-03-07T12:07:40.390 回答
2

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

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

于 2012-10-12T20:38:57.323 回答
1

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

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

基本上你从标准输入读取一个 int 并使用它来构建一个Throws项目Throws(val)

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

于 2012-10-12T20:40:10.187 回答
1

试试这个:

enum Throws {R = 'R', P = 'P', S = 'S'};
char userInput;
cout << "What is your throw : ";
cin >> userInput;
Throws userThrow = (Throws)userInput;
于 2012-10-12T20:58:22.027 回答
1

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

于 2012-10-12T21:11:28.307 回答
0

你可以试试这个:

int userOption;
std::cin >> userOption;

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

Throws userThrow = static_cast<Throws>(userOption);

如果要在枚举中分配用户输入,请使用以下代码

Throws R = static_cast<Throws>(userOption);

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

于 2017-10-29T11:35:18.760 回答