Home > Mobile >  Why is my loop not restarting to the first iteration? C
Why is my loop not restarting to the first iteration? C

Time:11-19

I'm making a Dice Game in C . I was wondering why it doesn't restart the loop. The game is Best of 3. It's supposed to restart the loop as long as the player wants to keep playing. However it only restarts the loop once. The second time I press 'Y' or yes in this case it just exits the program.

I've tried putting the restart in a nested while loop but it doesn't seem to work either.

restart:    

while ((pWin != 2) && (cWin != 2))
{
    pDice1 = rand() % 6   1;
    cDice1 = rand() % 6   1;


    cout << "Player score is: " << pDice1 << endl;
    cout << "Computer score is: " << cDice1 << endl;

    if (cDice1 > pDice1) {
        cout << "Computer wins!" << endl << endl;
        cWin  ;

    } if (pDice1 > cDice1) {
        cout << "Player wins!" << endl << endl;
        pWin  ;
    } if (pDice1 == cDice1) {
        cout << "It's a draw!" << endl << endl;
    } if (pWin > cWin) {
        cout << "Player wins this round! Do you wish to keep playing?" << endl;
        cin >> Y;
        if (Y == 'y') {
            goto restart;
        }
        else {
            exit(0);
        }
    }if (cWin > pWin) {
        cout << "Computer wins this round! Do you wish to keep playing?" << endl;
        cin >> Y;
        if (Y == 'y') {
            goto restart;
        }
        else {
            exit(0);
        }
    }
        
        

}

CodePudding user response:

First, is this all your code? I noticed most of your variables seem to be declared outside of the provided code block. If so, is your "Y" being declared as a char and not a string type to match your condition type?

It looks like you are failing to set your pWin and cWin back to zero when it returns to the top. You can fix with:

restart:    
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6   1;
cDice1 = rand() % 6   1;


cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;

if (cDice1 > pDice1) {
    cout << "Computer wins!" << endl << endl;
    cWin  ;

} if (pDice1 > cDice1) {
    cout << "Player wins!" << endl << endl;
    pWin  ;
} if (pDice1 == cDice1) {
    cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
    cout << "Player wins this round! Do you wish to keep playing?" << endl;
    cin >> Y;
    if (Y == 'y') {
        goto restart;
    }
    else {
        exit(0);
    }
}if (cWin > pWin) {
    cout << "Computer wins this round! Do you wish to keep playing?" << endl;
    cin >> Y;
    if (Y == 'y') {
        goto restart;
    }
    else {
        exit(0);
    }
}
    
    

}

CodePudding user response:

Because you don't reset pWin and cWin to zero after a game.

You should fix that but also turn the goto into another while loop and make the guts of that while loop into a function maybe.

  • Related