0

Im working on a hangman game for class, i'm having trouble getting a random number. Everytime I run the code I get the same number. Not sure what the problem is here, anything would help.

string pickWord(){
    int random = rand() % 17;
    string word = ::wordList[random];
    cout << word << endl;
    return word;
} 

1 Answers1

4

You have to seed random with time, otherwise it will always be the same.

take a look at this:

http://www.cplusplus.com/reference/cstdlib/srand/

your code should look like this

string pickWord(){
    srand (time(NULL));
    int random = rand() % 17;
    string word = ::wordList[random];
    cout << word << endl;
    return word;
} 

and also you have to add an include

#include <time.h> 

This way, random will be dependant on the time, it is run, not on the compilation time.