在C ++中的if语句中使用多个条件 [英] Using multiple conditions in an if statement in C++
问题描述
我正在尝试在C ++中创建一个复杂的if语句,这将使我免于编写一大堆if语句,我想知道下面的代码是否真的有意义或我忽略了错误。
I am trying to create a complex if statement in C++ that will save me from writing a whole bunch of if statements, I am wondering if this code below actually makes sense or I am overlooking an error.
if(input==choice) {
cout << "Tie!" << endl;
}else if(input=="rock" && choice=="scissors"
|| input=="scissors" && choice=="paper"
|| input="paper" && choice=="rock") {
cout << input " beats " << choice << ", you win!" << endl;
}else if(input=="rock" && choice=="paper"
|| input=="scissors" && choice=="rock"
|| input=="paper" && choice=="scissors"){
cout << choice << " beats " << input << ", you lose!" << endl;
}
我想要实现的是:
"if input is x AND choice is y, OR if...."
基本上我正在测试多个if-and条件,以便在遇到任何if-and条件时执行一行代码。输出抛出不匹配'运算符||'错误。
Basically I'm testing multiple "if-and" conditions so that a single line of code will execute if it hits any of the if-and conditions. The output throws a "no match for 'operator||'" error.
推荐答案
你在输入错误输入=纸&&选择==摇滚)
,但我建议你修改代码而不是修复拼写错误。难怪你在这个巨大的条件下犯了错字。你有很多重复和混合逻辑与输出。如果您在包含上花费一些代码,则可以在代码中保存一些...
You have a typo in input="paper" && choice=="rock")
, but instead of fixing the typo I would suggest you to fix the code. No wonder you made a typo in this giant block of conditions. You have lots of repetion and mixing logic with output. If you spend some lines on includes, you can save some on code...
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
bool win(const std::string& input, const std::string& choice) {
static const std::vector<std::pair<std::string, std::string>> wins =
{ { "rock", "scissors" },
{ "scissors", "paper" },
{ "paper", "rock" }
};
return std::find(wins.begin(), wins.end(), std::make_pair(input, choice))
!= wins.end();
}
int main() {
std::string choice = "paper";
std::string input = "scissors";
if (win(choice, input)) { std::cout << "you win! \n"; }
else { std::cout << "you lose! \n"; }
}
作为下一步,您应该消除所有字符串,例如使用枚举作为在评论中讨论过。
As next step you should eliminate all that strings, eg by using enums as discussed in the comments.
这篇关于在C ++中的if语句中使用多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!