How should I properly seed srand()

86 views Asked by At

I have these snippets of code:

char letrarand()
{
    time_t t;
    srand(time(NULL));                                                  
    char randomletter = 'A' + (rand() % 26);
    return randomletter;
}

char criameses()
{
    int contador = 0;
    for (contador = 0; contador < 31;++ contador) 
        {
            *(pjaneiro + contador) = letrarand();
        }

Where pjaneiro is a pointer to a 31 element array. Theoretically this works and would assign a random letter to each element of the array, but as it turns out it always assigns the same letter.

My best guess as to why this happens is that the time() functions is only accurate to a second so the seed to the random number generator is always the same because my computer executes the code in less than one second. Is there a way for me to better seed the random number generator?

0

There are 0 answers