Hello, I am in school programming a game using SDL.

It's a simple game where the player shoots at ships, which spawns randomly.

For this I call random function rand() each time in the game loop, then using the modulus operator to determine wether a new enemy will spawn.

The problem is, the random function frequently returns the same numbers, here's an example of output from the random function.

r: 41
r: 18467
r: 26435
r: 26435
r: 26438
r: 26438
r: 26438
r: 18083
r: 14284
r: 22658
r: 29693
r: 26441
r: 26441
r: 26441
r: 26441
r: 26441

I can't post the whole code, and I don't know which information which could be relevant, but here's basically what it is:

#include <time.h>

int main ( int argc, char** argv )
{
    srand(time(0));
   ....

    bool done = false;
    while (!done)
    {
     int r=rand();
     if(r%50==0){
            //Spawn enemy
        }
       .....

So, what could the problem be? Help appreciated!

The probem is that you have to see seed the random generator with the srand function

As you can see, the OP already did that in his/her code.

@OP:
Here's a great page about using rand(), it will clear things up for you.

The probem is that you have to see seed the random generator with the srand function

The OPs code is seeding it.
Though I do wonder about the code the OP used to generate that output. How close was it to the code actually posted? Was srand(time(0)) being called before each rand() (it shouldn't be)?

Try running this code and see what output you get:-

#include <time.h>
int main ( int argc, char** argv )
{
   srand(time(0));
   for (int i = 0; i < 20; i++)
   {
      cout << rand() << endl;
   }
   return 0;
}

In most of (well known) C and C++ implementations rand is a very bad pseudo-random generator but it NEVER gets two equal numbers in succession (that's why it's a very bad...).
I think it's impossible to get 264412, 26441... if you don't seed the generator with the same value just before every rand call...

effective, this isn't a chat room. If you don't have anything to add then please don't reply. If everyone posted things like "Nice!" or "I agree!", then it would become difficult to find the useful information in a thread.

If you must share your enjoyment of a post, add to the poster's reputation with whatever pithy and cliche comments you'd like.

This article has been dead for over six months. Start a new discussion instead.