Как предложить пользователю перезапустить всю программу? - PullRequest
0 голосов
/ 03 марта 2019

Я хочу, чтобы пользователь выбирал между игрой снова или завершением программы, однако при появлении запроса, если они нажимают 'y', то же самое повторяется снова и снова вместо всей программы с самого начала.Я пробовал циклы while, циклы do / while, операторы if, переставляя код, но ничего не получалось.Любой совет?

#include <iostream>
#include <string>
using namespace std;

int main(){
    string animal = "fish";
    string guess;
    char choose = 'Y' ;
    int count = 0;//keeps a running total of how many times the user 
has guessed an answer.
    int limit = 5;//allows user to guess only 5 times, otherwise 
they loose the game.
    bool out_of_guesses = false;//to check whether the user has run 
out of guesses.

    cout << "I am thinking of an animal.\n" << endl;

    do{
        while(animal != guess && !out_of_guesses){//Nested while 
loop inside main loop to keep track of how many tries the user has 
attempted and to validate their answers.
        if(count < limit){
            cout << "Can you guess what animal I am thinking of?: ";
            getline(cin, guess);
            count++;
            if(animal != guess){
                cout << "\nHmm, nope. That's not the animal I'm 
thinking of." << endl;
                if(count > 2 && count <5){
                    cout << "I'll give you a hint. It lives in 
water." << endl;
                }
            }
        }
        else{
            out_of_guesses = true;
        }
    }//End nested while loop
        if(out_of_guesses){
            cout << "\nI'm sorry, but you are out of guesses." << 
endl;
        }
        else{
            cout << "\n*** Good job! You guessed the correct animal! 
***" << endl;
            cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
        }

    //The do-while loop is there to ask the user if they wish to 
play the game again.
    cout << "Would you like to try again?(y/n): ";
    cin >> choose;
        if(choose == 'N' || choose == 'n')
            break;
    }while(choose == 'Y' || choose == 'y');
    return 0;
}

1 Ответ

0 голосов
/ 03 марта 2019

bool out_of_guesses = false; должно быть между while(true) и while(animal != guess && !out_of_guesses), а не за пределами первого цикла while.Поскольку наше условие цикла while всегда ложно, а затем оно входит в него.

Вы также должны сбросить переменную guess между этими двумя циклами, иначе может произойти то же самое (false, в то время как цикл) в случаеответа найден.

Здесь приведен код с некоторым рефакторингом / рецензией, который я использовал в качестве заглавной буквы для обработки любой типографии ответа.Я также удалил переменную вне догадки, чтобы использовать счетчик и ограничить его.

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    const std::string animal = "FISH";
    const int limit = 5;

    do
    {
        std::cout << "I am thinking of an animal.\n";

        int count = 0;
        std::string guess;    

        while(animal.compare(std::toupper(guess)) != 0 && count < limit)
        {
                std::cout << "Can you guess what animal I am thinking of?: \n";
                std::cin >> guess;
                count++;
                if(animal.compare(std::toupper(guess)) != 0)
                {
                    std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
                    if(count > 2)
                    {
                        std::cout << "I'll give you a hint. It lives in water.\n";
                    }
                }
            }
        }//End nested while loop

        if(count >= limit)
        {
            std::cout << "\nI'm sorry, but you are out of guesses.\n";
        }
        else
        {
            std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
            std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
        }

        char choose = 'Y' ;
        std::cout << "Would you like to try again?(y/n): ";
        std::cin >> choose;
        if(std::toupper(choose) == 'N') break;

    } while(true);

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...