samedi 2 mars 2019

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?

#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;

    while(true){
        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;
}

Aucun commentaire:

Enregistrer un commentaire