Random Response Generator

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;

int main()
{
string mystr;
cout << "Hello. How are you today? \n";
getline(cin, mystr);
const char* possibleanswers[5] = {
"sorry", "that sucks", "who cares", "whatever", "get over it"
};
cout << possibleanswers[rand() % 5]<< "\n";
getline(cin, mystr);
cout << possibleanswers[rand() % 5] << "\n";
getline(cin, mystr);
cout << possibleanswers[rand() % 5] << "\n";
getline(cin, mystr);
cout << possibleanswers[rand() % 5] << "\n";
getline(cin, mystr);
cout << possibleanswers[rand() % 5] << "\n";
}
You need to seed the random number generator.

Put this at the start of main:

1
2
3
4
5
6
7
8
9
10
#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
    //... 
Ok cool. I will try that. Just curious, what does the

srand ( (unsigned) time(0);

actually do? (trying to understand, not just mimic).
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.
That makes perfect sense. Also, it worked in the program. Thank you so much!
Topic archived. No new replies allowed.