检查有效的用户输入c ++

时间:2019-03-06 13:37:16

标签: iostream getline

我正在玩纸牌游戏。此功能提示用户在交易卡或保留卡(通过)之间做出选择:

void Game::playerTrade(Player &p, Player &neighbor, bool last){
    std::cout << "\n";
    std::string move;
    std::cout << p.getName() << ", it's your turn! " << std::endl;
    std::cout << "Your card is " << p.getCard().toString() << std::endl;
    std::cout << "Would you like to trade or pass? (T|P)";
    getline (std::cin, move);

    while(move != "t" && move != "T" && move != "p" && move != "P") {
        std::cout << "Please make a valid choice " << std::endl;
        std::cout << "Would you like to trade or pass? (T|P)";
        getline (std::cin, move);
    }
    // FIXME the first time it asks to trade or pass it immediately goes into this while??

    if(move[0] == 't' || move[0] == 'T'){
        if(last)
            p.tradeWithDeck(gameDeck);
        else
            p.trade(neighbor);
    }
    else if(move[0] == 'p' || move[0] == 'P')
        std::cout << p.getName() + " passes" << std::endl;
}

这是我得到的输出:

Your card is 3 of Clubs
Would you like to trade or pass? (T|P)Please make a valid choice 
Would you like to trade or pass? (T|P)

由于某种原因,在用户输入其选择之前,似乎执行while循环。我该如何解决?

0 个答案:

没有答案