在 switch 语句中输入字符以进行C++时用户输入错误

User input error when inputting a character within a switch statement for C++

本文关键字:输入 C++ 错误 用户 switch 语句 字符      更新时间:2023-10-16

我对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::mapstd::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 的变量类型
  • cingetline,这需要整条生产线。
  • Switch 语句更改为 if 语句,以便能够像您一样比较完整的字符串。