error when i give sleep(1000), to make srand() work, in visual C++

804 Views Asked by At

i have following program:

srand((unsigned) time(NULL));
for (int w = 0; w < 10; w++) {
    int ran_x;
    ran_x = rand() % 255;
    cout << "nRandom X = " << ran_x << endl;
    //some more lines of code
    Sleep(1000);
}

I am running it on visual c++ 2008, When I run this program, it doesnt show any errors or warnings. But when I run it, some of the times it runs fine, and some of the times it stops in the middle and gives this error "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information."

What shall I do? Is it possible to do it with out using Sleep() function and still get randomly generated values. Because if I remove Sleep(1000), it doesnt give any error but it doesnt gives random values either

5

There are 5 best solutions below

0
On

What's the content of "some more lines of code"?

<psychic debugging>I bet you have code that there that, directly or indirectly, depends on the random value you generated earlier. This code will likely be a division, or involve setting the length of some container, and borks when the generated random number is 0.</psychic debugging>

0
On

Works without any problems with gcc

#include <iostream>
#include <cstdlib>

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

    for (int w = 0; w < 10; w++)
    {
        int ran_x = rand() % 255;

        std::cout<<"\nRandom X = " << ran_x << std::endl;

        sleep(1);
    }

    return 0;
}
2
On

Obviously you shouldn't have to sleep. Code looks sane to me, as long as you only call srand() once. If you call this entire block of code multiple times intra-second, then time(NULL) will be returning the same second value and srand() will start the pseudo-random number generation at the same number, selecting the same set of 10 subsequent numbers....

2
On

Seems to me your program should work perfectly without the sleep call. In fact seems to work for me on VS2008 perfectly. I believe your problems must be in code that you have removed thinking it irrelevant.

0
On

The code snippet you posted is hardly responsible for your application terminating, Sleep or not.

Because if I remove Sleep(1000), it doesnt give any error but it doesnt gives random values either.

Well, rand() certainly gives you pseudo-random numbers, although the PRNG implementation might not return random values evenly distributed along the bits of the returned value, i.e. in many implementations, the higher bits are changing more often than the lower bits, which is why your code is a poor choice for selecting a random value between 0 and 255.

In general, I'd recommend switching from your standard library's rand/srand to an implementation like boost's mersenne twister (boost::random), or at least see

http://c-faq.com/lib/randrange.html