如何从 C++ 中的 UserInput 字符串为 switch case 分配枚举
我正在编写这段代码,它接受一个 char userinput
并使用 switch 语句执行相应的命令。但是,由于 C++
switch 语句只能读取整数和枚举,因此我不确定如何合并它。用户输入必须是字符。有什么想法吗?我知道 charInput
>> enumInput
不起作用,但我不知道该怎么做。
int main(int argc, char** argv) {
enum charCommand { i, d, s, n, r, a, m, t, p, l, q };
charCommand enumInput;
while (mainLoop) {
cout << "enter valid input" endl;
char charInput;
printf("Enter a command: ");
cin >> charInput;
charInput >> enumInput;
switch (charInput) {
case i: {
printf("This is case i");
exit(0);
} //case i
default: {
cout << "invalid command, try again!\n";
}
}
};
}
I'm writing this code that takes in a char userinput
and uses the switch statement do execute the respective command. However because C++
switch statements can only read ints and enums, I'm not sure how to incorporate this. The user input must be a char. any ideas? I know charInput
>> enumInput
doesn't work but I'm not sure what to do.
int main(int argc, char** argv) {
enum charCommand { i, d, s, n, r, a, m, t, p, l, q };
charCommand enumInput;
while (mainLoop) {
cout << "enter valid input" endl;
char charInput;
printf("Enter a command: ");
cin >> charInput;
charInput >> enumInput;
switch (charInput) {
case i: {
printf("This is case i");
exit(0);
} //case i
default: {
cout << "invalid command, try again!\n";
}
}
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现此目的的一种方法是将输入的实际字符映射到其相应的
enum
:One way to accomplish this is to map the actual character entered to its corresponding
enum
:这里不需要
enum
。switch
适用于 char,因为char
可转换为int
。因此,如果我们这样定义一个char
:..然后打开它:
这有效,因为
'a'
可以转换为int
( ASCII 值)。所以这也可以写成:例子:
上面的例子是有效的。对于您的情况,我会将您的程序重写为:
另外,请考虑不在代码中使用以下内容:
..因为它被认为是一种不好的做法。有关这方面的更多信息,请查找 为什么考虑“使用命名空间 std”这是一种不好的做法。
There's no need for an
enum
here.switch
works with char becausechar
is convertible toint
. So if we define achar
as such:..and then switch on it:
This works because
'a'
can be converted toint
(ASCII value). So this can also be written as:Example:
The above example works. For your case, I would rewrite your program as:
Also, consider not using the following in your code:
..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.