Don't Know why this doesn't work.

In this it is supposed to repeat the while function when the answer inputted is the same as "r". It does not do that and I have no idea why. i have it couting whether it is true that input == r and it always comes up as true but it does not repeat the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   while (input == r)
        {
        cout << string(5, '\n');
        int r = (rand() % 9) + 1;
        random(r);
        score++;
        cin >> input;
        if (input == r)
        {
            input = r;
        }
        if (input != r)
        {
            gameoverPage(score);
            input != r;
        }

        cout << (input == r);
        }
You have 2 separate variables named 'r'.

In order for line 1 to compile without error, your r variable must have been declared above it. We'll call this variable r1.

You are declaring r again on line 4. We'll call this r2.

This means that everything between lines 4 and 19 are using r2, whereas everything above and below it are using r1. So ultimately, the loop condition is checking r1, but the loop body is modifying r2.


Long story short... get rid of the re-declaration on line 4 and simply use r1:

1
2
3
4
5
// BAD:
int r = (rand() % 9) + 1;  // <- note, the 'int' creates a new variable

// GOOD:
r = (rand() % 9) + 1; // <- no 'int' means you want to use an existing variable 
Last edited on
Thanks. That fixed it.
Topic archived. No new replies allowed.