I'm currently developing a game (And no, just because that's the case doesn't mean this belongs in game development), and I've run into a problem.

Basically, I need to generate a random number.
The number needs to stay the same after it is generated once.
The code is in an infinite loop, which makes it very difficult.

I've tried getting around it by making it choose the number at the top where all the other global variables are declared, but this makes the variable choose a value before srand is even activated, so it just picks the same number each time.

Help?

Recommended Answers

All 2 Replies

umm something like so:

struct ConstantRandom{
  int randNum;
  bool isFirstTime;
 ConstantRandom(): isFirstTime(true), randNum(0){};
 int operator()(){
   if(isFirstTime){ randNum = rand();  isFirstTime = false;}
   return randNum;
};
int main(){
 srand( time(0) );
 ConstantRandom cr;
 int i = cr(); //i equals some random number
 int j = cr(); // j should equal to i

Basically your just saving a state

I had to play around with it a bit, but it worked.
Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.