rand()

Hello, i'm writing a program that relies on creating many objects ,each containing a certain amount of random information. For example one of the member varibles has to contain a random name from say 10.

When i try to run the program the first object seems to work but every subsequent object has the same info. I'm fairly clear about the rand() and the srand() command, and i've put them both in the constructor - which is where i think i'm going wrong..?.

Should the srand() go in main() or something ??
I'm fairly clear about the rand() and the srand() command, and i've put them both in the constructor

Are you doing this?
1
2
3
4
A::A(){
   srand(time(NULL));
   some_variable = rand();
}

if that so, you just need to call srand once in your whole program (to assure the randomness)
You're getting the info repeated because time returns in seconds, so the seed is always the same.
Should the srand() go in main() or something ??


Yes.

srand() should be called exactly once by your program. Not once for each random number, not once for each A object, once total. Throw it in at the beginning of main() and then forget about it and never call it again.
Thanks guys.
Topic archived. No new replies allowed.