gpt4 book ai didi

c++ - 如何使用 switch 语句和完整的单词而不是首字母来编写相同的代码?

转载 作者:行者123 更新时间:2023-11-28 04:05:21 25 4
gpt4 key购买 nike

请考虑以下代码:

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
enum object {rock, paper, scissors};
object player1, player2;
cout << " "Enter "r" for rock, "p" for paper or "s" for scissors:";
char p1, p2;
cin >> p1 >> p2;

if (p1 == 'r') {player1 = rock;}
else if (p1 == 'p') {player1 = paper;}
else if (p1 == 's') {player1 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}

if (p2 == 'r') {player2 = rock;}
else if (p2 == 'p') {player2 = paper;}
else if (p2 == 's') {player2 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}

if (player1==player2) cout <<"objects are equal";
else if (player1==rock && player2==paper) cout << "player 2 is the winner";
else if (player1==rock && player2==scissors) cout<<"player 1 is the winner";
else if (player1==paper && player2==rock) cout << "player 1 is the winner";
else if (player1==paper && player2==scissors) cout <<"Palyer 2 is the winnder";
else if (player1==scissors && player2==paper) cout << "Player 1 is winner";
else cout <<"Player 2 is the winner";
cout << endl;
}

当用户必须给出完整的单词(石头、剪刀、布)而不是输入的首字母时,如何用 switch 语句重写上面的代码。

更新:我已经用 switch 转换了部分代码,但我很想看看我是否可以将它用于整个代码:

例如:

switch (p1) {
case 'r': player1=rock; break;
case 'p': player1=paper; break;
case 's': player1=scissors; break;
}

代替

if (p1 == 'r') {player1 = rock;}
else if (p1 == 'p') {player1 = paper;}
else if (p1 == 's') {player1 = scissors;}
else {cout << "invalid input, play again" << endl; exit(1);}

最佳答案

你不能这么简单。 switch 不适用于字符串。但是,您可以绕过这个问题并在进行切换之前计算 object:

std::string player1Input, player2Input;
//...
std::cin >> player1Input >> player2Input;

object player1Choice = getChoice(player1Input);
object player2Choice = getChoice(player2Input);

getChoice 可能如下所示:

object getChoice(std::string input)
{
if(input == "rock")
return object::rock;
else if(input == "paper")
return object::paper;
else if(input == "scisor")
return object::sciscor;
else {
//invalid input
}
}

然后你就可以使用你的开关了:

switch(player1Choice)
{
case object::rock:
switch(player2Choice)
{
case object::rock: //rock vs rock
break;
...
};

break;
...
}

关于c++ - 如何使用 switch 语句和完整的单词而不是首字母来编写相同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58822741/

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