Hey guys. I'm new to C++, and looking for some help. I'm trying to use a random response generator. I found a ton of information on this site, and I'm running a (very simple) program that is using 5 responses. My issue is, that every time I run the program (debug in visual express), it generates the same responses, in the same order, every time. I will post what I have below, and I'm hoping that it's just something simple that I am missing. Thanks!!
#include <iostream>
#include <string>
using namespace std;
#include <iostream>
#include <string>
#include <ctime> // <- include this for time()
#include <cstdlib> // <- include this for rand(), srand()
int main()
{
srand( (unsigned)time(0) ); // <- put this here.. call it once and only once
//...
rand() is a mathematical psuedo random number generator (PRNG). It's basically a mathematical formula that takes an input number, and runs it through a big computation to produce an output number. The computation effectively "scrambles" the number so it appears to be random.
That output number then becomes the input number for the next call to rand()... so when you call it again, the number is scrambled again.
However, this math formula has to start somewhere. It has to start with some input. If you leave it alone... it will start with the same input every time -- which will produce the same stream of generated numbers every time.
Calling srand() "seeds" the PRNG, giving it a new starting point. By using the current time (something that is almost guaranteed to be different and unique each time the user runs the program), you effectively get a new starting point -- and therefore a new stream of random numbers -- every time.