Using multiple conditions in an if statement in C++ -
i trying create complex if statement in c++ save me writing whole bunch of if statements, wondering if code below makes sense or overlooking 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 << ", win!" << endl; }else if(input=="rock" && choice=="paper" || input=="scissors" && choice=="rock" || input=="paper" && choice=="scissors"){ cout << choice << " beats " << input << ", lose!" << endl; }
what trying achieve is:
"if input x , choice y, or if...."
basically i'm testing multiple "if-and" conditions single line of code execute if hits of if-and conditions. output throws "no match 'operator||'" error.
you have typo in input="paper" && choice=="rock")
, instead of fixing typo suggest fix code. no wonder made typo in giant block of conditions. have lots of repetion , mixing logic output. if spend lines on includes, can save 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 should eliminate strings, eg using enums discussed in comments.
Comments
Post a Comment