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.
The C function
srand
is meant to be used in combination with the C functionrand
. These are separate functions from those in C++'sstd::experimental
header. Therandint
function from the latter is meant to be used with thereseed
function from the same header:However, there is no need to use experimental features here. Since C++11, there is
std::uniform_int_distribution
:This method is more flexible than the one from the C standard library and should, generally, be preferred in C++.