The code below will output the same 10 numbers every time the program is ran.
#include "stdafx.h" // - Visual Studio only #include <stdlib.h> #include <iostream> using namespace std; void genRanNum() { int num = 10; do { cout << rand() % 10 << endl; num--; } while (num>0); } int main() { genRanNum();//--produce 10 random numbers cin.get();//-- pause return 0; }
To generate a seed that will be different to the default output but same every time it is used, use srand(23232) - with numbers of your choice.
#include "stdafx.h" // - Visual Studio only #include <stdlib.h> #include <iostream> using namespace std; void genRanNum() { int num = 10; do { cout << rand() % 10 << endl; num--; } while (num>0); } void seedGen(int seed=0) { srand(seed); } int main() { seedGen(3245);//--generate a seed based on numbers genRanNum();//--produce 10 random numbers cin.get();//-- pause return 0; }
And finally to produce a pseudo-random seed every time the program is used, parse current time value into the srand(time(0)) function as a parameter. Include <time.h> header to work with time.
#include "stdafx.h" // - Visual Studio only #include <stdlib.h> #include <iostream> #include <time.h> using namespace std; void genRanNum() { int num = 10; do { cout << rand() % 10 << endl; num--; } while (num>0); } void randSeedGen() { srand(time(0)); } int main() { randSeedGen();//--generate a random seed based on time genRanNum();//--produce random 10 number cin.get();//-- pause return 0; }