带有循环的 C++ 枚举行为

时间:2021-07-01 18:08:47

标签: c++ loops input enums

我正在尝试此代码

int n,k;
enum Throws {R, P, S};
int userInput;
for(int i=0;i<3;i++)
{
cin>>userInput;
cout<<(Throws)userInput;
}

为什么这段代码不将 R 作为输入并提供 0 作为输出并等待下一个输入而是将 000 作为任何值的输出 预期输出: 输入-R 输出-0 输入-S 输出-2 输入-P 输出-1 但我得到了这个 输入-R(或P或S) 输出- 000 (发生循环退出) 不完全确定代码如何感知输入,因为我理解枚举应该像 R=0,P=1,S=2 一样,其中 R,P,S 应该变得像整数。 我做错了什么,或者我的理解是错误的?请有人解释怎么做? 谢谢

input output window:
input-R
output-R
input-P
output-P
input-S
output-S

这就是我想要得到的输出 我尝试将枚举本身作为输入,但它给出了错误 喜欢

enum Throws q;
cin>>q;
it gives error: no match for ‘operator>>’```

1 个答案:

答案 0 :(得分:0)

我不完全确定这是否是您想要的,但是下面让用户输入一个字符,然后将相应的枚举值分配给一个变量,然后再次打印相应的字符。这一切都不是免费的,如果你想拥有这样的映射,你需要自己实现:

#include <unordered_map>
#include <iostream>
#include <algorithm>

enum Throws {R, P, S};

int main(){
    std::unordered_map<char,Throws> mapping{{'R',R},{'P',P},{'S',S}};
    std::unordered_map<Throws,char> reverse_mapping{{R,'R'},{P,'P'},{S,'S'}};
    char input;

    std::cin >> input;
    Throws t = mapping[input];
    std::cout << "user entered " << input << ", corresponding enum value is " << t << "\n";

    std::cout << "the character for enum value " << t << " is " << reverse_mapping[t] << "\n";
}

例如当用户输入 1 时,输出为:

user entered P, corresponding enum value is 1
the character for enum value 1 is P

在您的代码中,userInput 是一个 int 并且当用户输入一个字符时,例如 R,那么 userInput 具有表示该字符的整数值,以 ascii 表示82。该 82 与枚举值 R 无关。另一方面,如果用户输入 0,那么您可以通过 0 将该 R 转换为 static_cast<Throws>(userInput) 的值,这实际上与您代码中的转换相同,只是它不像您对用户输入 R 所期望的那样工作。

相关问题