gpt4 book ai didi

c++ - 如何使用带有字符串的开关?

转载 作者:行者123 更新时间:2023-11-30 00:51:42 24 4
gpt4 key购买 nike

我正在尝试创建一个猜谜游戏,如果玩家猜对了许多字符串中的一个,他就会获胜。虽然 switch 语句可以使用 switch 括号中的单个字母,但如果我将字符串放入其中,它就无法工作。

#include "stdafx.h"
#include < iostream>

using namespace std;

class Player
{
public:

void Guess();
};
void Guess()
{
char guess;
char* word1 = "Dog";
char* word2 = "Cat";


cout <<"Welcome to guess the word. Get ready..." <<endl;
cout <<"Guess the word: " <<endl;
cin >>guess;

for (int i = 0; i <= 3; i++) //give the player 3 trys at guessing
{

switch(guess)
{
case 'Dog':
cout <<"Dog is correct." <<endl;
i = 3;
break;

default:
cout <<guess <<" is incorrect." <<endl;
cin >>guess;




}
}
}

int main()
{
Guess();
char f;
cin >>f;
return 0;
}

最佳答案

您不能将 switch 与字符串一起使用。这是不正确的:

case 'Dog': ...

Dog 是多字节字符常量,而不是字符串。编译器应该对此发出警告。

此外,guess 是单个字符。它也需要是一个字符串。你应该使用 std::string,像这样:

std::string guess;
cout <<"Guess the word: " <<endl;
cin >>guess;
if (guess == "Dog") ...

关于c++ - 如何使用带有字符串的开关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20870621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com