Search code examples
c++randomsrand

C++ random number generator


I am writing an lottory application. I have a function called generateLotteryNumbers this takes in an array and fills that array with 5 random numbers. What I want to do is have this function produce a different set of random numbers every time this function is called.

void generateLotteryNumbers(int lotteryNumbers[])
{

    srand (time(NULL));
    const int arraySize = 5;
    int index = 0;

    while (index < arraySize)
    {
        lotteryNumbers[index] = rand() % 50 + 1;
        cout << lotteryNumbers[index] << endl;
        index++;
    }
}

The output at the moment is eg:

5
24
45
26
47

Repeated twice.


Solution

  • Call srand exactly once, usually early in the code in main.