0
votes

I want to use a random-number-generator in c++ to make a maths quiz with randomly-generated numbers.

My problem is that using time(0) is only accurate to a single second. In the IDE that I am using (NetBeans 8.2), a message appeared when hovering over srand(time(0)) with the message:

Image of the text

This is a weak random number generator; it is not useful for security purposes. Alternative: getrandom(void *buf,size_t buflen, unsigned int flags);/dev/urandom;

I could not find anything online about getrandom. I was wondering if anyone could shed some light on the syntax of getrandom? How to use it?

1
Do you want to make a random number generator or use one?juanchopanza
Do you really need security strength for your random generator?Holt
I am just making a randomly generated maths test as a 'first project' for learning C++ but the numbers are always the same when generated in the same second so I'd like a better way of making random numbersDoot
@user9464295 You should srand only once, at the beginning of your program. But nowadays, there are better way of generating random number, such as the random standard library linked by @DanielJour.Holt

1 Answers

3
votes

You should stop using srand / rand since these are old ways of generating random numbers. Since C++11, there is a random standard library:

#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 100);

// To generate a number:
dis(gen);

Quick explanation:


std::rand is also a pseudo-random number generator, but the random engine is implementation-defined, and you need to use srand to initialize it:

// Call srand once at the beginning of the program:
srand(time(0));

// Then you use rand() without (usually) calling srand() again:
rand();
rand(); 

But as you noticed, std::time usually returns a number of seconds, so if you run your program twice in a second, you will probably get the same output.


getrandom is a non-standard function (maybe POSIX?), there is really no needs to use it for a game now that the random standard library is available.