在 switch 语句中输入字符以进行C++时用户输入错误
User input error when inputting a character within a switch statement for C++
我对C++相当陌生,因为我目前正在研究这个语言工具的switch语句。我的代码有问题,因为我缺乏进行相关配置所需的理解,这将有助于解决可能的输出问题。此问题围绕输出默认开关选择的问题解决,而不是输入相关输入字符时的理想情况:
#include <iostream>
using namespace std;
int main()
{
char Poke;
cout << "Please select your starter Pokemon:" << endl;
cin >> Poke;
switch (Poke) {
case 'Bulbasaur':
cout << "You have selected " << Poke << endl;
break;
case 'Charmander':
cout << "You have selected " << Poke << endl;
break;
case 'Squirtle':
cout << "You have selected" << Poke << endl;
break;
default:
cout << "Entry Unknown" << endl;
break;
}
}
是的,此代码基于第一代的原始三个入门口袋妖怪。每当我在命令提示符窗口框中选择、选择和输入"Charmander"时,由于某种原因,它不会读取我的输入,只会输出默认值"条目未知":
命令提示符输出问题
抱歉,我无法嵌入图像。没有足够的声望点:/
>'Bulbasaur'
是一个多字符文本(请参阅此处的语法 6)。 "Bulbasaur"
将是一个字符串(请注意不同的引号字符)。不能使用字符串或std::string
switch
。要实现,您需要使用一系列if
或使用容器,例如 std::map
或 std::unordered_map
.
此外,在char Poke; cin >> Poke;
中,类型 char
表示Poke
是单个字符。您只能在 Poke
中存储单个字符。请改用std::string
。
我目前正在研究这个语言工具的开关语句。
switch 语句只能用于整数值,不能用于用户定义类型的值。因此,即使您尝试使用C++的 std:string 类,它也不会起作用。由于您的主要要求是使用 switch-case
,请尝试如下操作:
#include <iostream>
using namespace std ;
int main()
{
char Poke;
cout<<"Please select your starter Pokemon:"<<endl;
cout<<"b for Bulbasaur, c for Charmander, s for Squirtle"<<endl;
poke = getchar(); //Take one char from standard input
switch(Poke){
case 'b' :
cout<<"You have selected "<<Poke<<endl;
break;
case 'c' :
cout<<"You have selected "<<Poke<<endl;
break;
case 's' :
cout<<"You have selected"<<Poke<<endl;
break;
default:
cout<<"Entry Unknown"<<endl;
break;
}
}
你应该看到一些基本的输入/输出C++教程,如下所示:
http://www.cplusplus.com/doc/tutorial/basic_io/
另请记住,switch
只能与整数值一起使用。
我已经进行了必要的更改,这工作正常:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Poke;
cout << "Please select your starter Pokemon:" << endl;
getline(cin, Poke);
if (Poke == "Bulbasaur")
cout << "You have selected " << Poke << endl;
else if (Poke == "Charmander")
cout << "You have selected " << Poke << endl;
else if (Poke == "Squirtle")
cout << "You have selected" << Poke << endl;
else
cout << "Entry Unknown" << endl;
}
必要的更改是:
-
Poke
从字符到 std::string 的变量类型 - 从
cin
到getline
,这需要整条生产线。 - 将 Switch 语句更改为 if 语句,以便能够像您一样比较完整的字符串。
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type