Using multiple conditions in an if statement in C++

后端 未结 1 1587
抹茶落季
抹茶落季 2021-01-28 01:08

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

相关标签:
1条回答
  • 2021-01-28 01:41

    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.

    0 讨论(0)
提交回复
热议问题