Swallows - 11 months ago 73

C++ Question

I'm trying to automate test cases for my program and i wanted to generate random strings of numbers to test with... First test will be with base 2 numbers, so i want to generate 0's and 1's, of a random length n, where n is from 1 to 100. This is what i have so far, and it keeps returning the same string, (same length) and only generates either a 1, or a 0 for the entire length of the string.

`int digNum = rand() % 100 + 1;`

int num;

for(int i = 0; i < digNum; i++) {

num = ((double) rand() / (RAND_MAX)) + 1;

s1 = s1 + to_string(num);

}

cout << s1 << endl;

Thoughts?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

**For the 0/1 problem :**

num = rand()%2;

Will generate a number that is 0 or 1 more simply. With your current expression, rand()/RAND_MAX is always <1, unless rand()==RAND_MAX, in which case it equals 1 . Adding 1 gives almost always 1, or 2 if rand()==RND_MAX

**For the constant result**

Even if rand() returns a pseudo random sequence, it will always generate the same sequence at program start by default. The result will be different if you call it a second time in the same program, as you advanced in the random number sequence. If you want the first calls to rand() of each proces run tu return different results, you have to call

```
srand(time(NULL));
```

before calling rand()

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**