Ending a while loop

I wrote a really basic game that makes the user guess a number between 1 and 100 to practice using loops (just started learning them), but when the correct number is entered the loop keeps running. Thoughts?

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>

using namespace std;

void guessTooHigh() //output is guess is too high
{
    cout << "You're guess was too high\n" << endl;
}

void guessTooLow()
{
    cout << "Your guess was too low\n" << endl; //output is guess is too low
}

void guessCorrect()
{
    cout << "Well done, you guessed correctly\n" << endl; //output is guess is correct
}

int main()
{
    int aim = 32; //number that the user aspires to guess
    int x; //introducing the value so the while loop knows to look for it
    while (x != aim) //keep asking for a guess whilst the guess does not equal the aim (32)
    {
        cout << "Please enter an integer between 0 and 100" << endl; //ask for guess
        int x;
        cin >> x;

        if (x < aim)
        {
            guessTooLow();
        }

        else if (x > aim)
        {
            guessTooHigh();
        }

        else
        {
            guessCorrect();
        }
    }


    return 0;
}

user break; under guessCorrect();
Fixed now, thanks! How exactly does that function work/what does it tell the program?
don't use break there. your logic is correct (while x != aim) the loop keeps going on, when they're equal the loop finishes.
the problem is that you declare the int x twice, out of the main loop and again inside it.
the outer x is used in the line "while (x != aim)", and the inner x is used in your if-else statments. you're confusing the scopes of two integeres who have the same name - 'x'.

long story short: remove line 27 and it should work.
Last edited on
Thank you very much!

Break tells your program to break out of the loop. You have indeed declared x twice as Stauricus said though, just remove line 27
Topic archived. No new replies allowed.