Random Integer wont regenerate new value

For this "Number Guessing Program" the same input '42' will win the game every time. I was wondering how to get the number to regenerate each time the program is re ran.

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
#include <iostream>

using namespace std;

int main()
{
    // nNumbertoGuess - a random number between 1 and 50
    int nNumbertoGuess = rand() % 50 + 1;
    // nGuess - users guess
    int nGuess = 0;
    // Guessed - Conditional statement for our game loop
    // to check and see if the user has guess the number correctly yet
    bool Guessed = false;

    while(!Guessed)
    {
        // Output to the user and generate a response
        cout << "Enter a random number between 1 and 50 below or 0 to exit\n";
        cin >> nGuess;

        // If we guessed properly
        if(nGuess == nNumbertoGuess){Guessed=true;cout<<"win!\n";}
        // Incase we want to stop playing
        if(nGuess == 0){break;}
        // Make sure our user can only guess the number between 1-50
        if(nGuess > 50 || nGuess < 1){cout<<"Invalid input try again\b";}
        // If the user guessed wrong
        if(nGuess != nNumbertoGuess){cout<<"Bad guess! Try again\n";}
        // Let the user know if theyre too high
        if(nGuess > nNumbertoGuess){cout<<"too high!\n";}
        // Let the user know if theyre too low
        if(nGuess < nNumbertoGuess){cout<<"too low!\n";}
    }

    // Tell the user the game ended
    cout << "Game over!\n";
    return 0;
}


Thank you if you can help.
Last edited on
Include the <ctime> header and seed rand at the beginning.

srand(time(NULL))
<ctime>'s srand(time(NULL)) works! :)
Just had to initialize the seed before setting the random variable! :)
Thanks!
Because 42 is always the answer to life, the universe, and everything, duh!
Topic archived. No new replies allowed.