Loop doesn't end

hello thanks for your help in advance. i cant figure out why my loop keeps going and doesn't end when I put in 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
 int randNum = 0, userGuess = 0;
 bool play = true;
 srand(time(0));

 do{

    cout << "Welcome to random number guessing game, guess a number from 1 - 10 (0 to end game): ";
    cin >>  userGuess;

    if (userGuess == 0){
        play = false;
    }

    randNum = rand() % 10 + 1;
    cout << "Rand num = " << randNum;

    while (userGuess != randNum){

        if (userGuess > randNum){
            cout << "Number is smaller";
        }
        else if (userGuess < randNum){
            cout << "Number is bigger";
        }
        else if (userGuess == randNum){
            cout << "You win, the winning number is: " << randNum;
            break;
        }

        cout << ", guess again: ";
        cin >> userGuess;

    }


 }while(play);


 cout << "Game ended";
 return 0;
}
The loop condition is tested on line 43 so when play is set to false on line 18 it will first run all the code between line 20 and 42 before exiting the loop.
Last edited on
the check for play is in the outer loop.
the inner loop will not stop until the player guesses the number...
you need
while (userGuess != randNum && userGuess)

which will fix it but is sort of a bandaid.
to correct it correctly you probably want to move the userguess/play logic into the innner loop and keep the while play on the outer loop as well, so that *both* loops end if they choose zero.
Topic archived. No new replies allowed.