mardi 29 août 2017

Generating true random numbers inside of a header file in C++

In C++, I am trying to define several functions inside a custom header file, say random.h, to generate random integers using them. I,ve included the necessary header files and made a namespace like the following inside my header file:

namespace myrand {
   int random()
   {
      srand(time(0));
      return rand();
   } 
}

Then I called this random function in my main function inside a for loop like this (I have included the header file and used the namespace ...):

for(int n=0; n<10; n++)
{
   cout << random() << endl;
}

I expected to get 10 different true random numbers, but what I get is 10 times repetition of a random number. When I use the same functions (srand(), time(0), rand()) inside the main function I get the expected result, but when I put them inside a function and put that function inside a header file and call it the result is as I said a repetition of random numbers. So I thought maybe I am missing some point about defining a function in a custom header file or about calling it.

So my question is how can I make true random integers using a function which is defined in a custom header file?




Aucun commentaire:

Enregistrer un commentaire