srand() is not working when used with non-constant parameter

164 Views Asked by At

I've got a problem with srand(). It only works when I use a number as a parameter, for example srand(1234), but when I try to use it with 'n' or with time (as below), then randint() keeps returning the same value.

#include <iostream>
#include <experimental/random>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    srand(time(nullptr));
    for (int i = 0; i < 4; ++i) {
        int random = experimental::randint(0, 9);
        cout << random;
    }
}

Thanks for your time.

1

There are 1 best solutions below

0
On

The C function srand is meant to be used in combination with the C function rand. These are separate functions from those in C++'s std::experimental header. The randint function from the latter is meant to be used with the reseed function from the same header:

#include <experimental/random>
#include <iostream>

int main() {
    std::experimental::reseed();

    for (int i = 4; i--; ) {
        int random = std::experimental::randint(0, 9);
        std::cout << random << '\n';
    }
}

However, there is no need to use experimental features here. Since C++11, there is std::uniform_int_distribution:

#include <iostream>
#include <random>
 
int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distrib(0, 9); // Default type is 'int'
 
    for (int i = 4; i--; ) {
        int random = distrib(gen);
        std::cout  << random << '\n';
    }
}

This method is more flexible than the one from the C standard library and should, generally, be preferred in C++.