Trying to figure out rand()

Hi,

Is the following code correct if I want to create a random number -RanNum - between 1 and 100 and convert it and store it into a string -s-?

1
2
        ranNum = rand() % (100 - 1);
        s = to_string(ranNum);


I should point out that those variables were declared outside of a for loop and that code is inside the for loop.

Thank you.
ranNum = rand() % (100 - 1);
is exactly same as:
ranNum = rand() % 99;
The remainder of division a % b must by definition be less than b.
Therefore, you will get values in [0..98]

Modern C++ has <random> that has higher quality generators than C's rand() and rather intuitive distributions:
http://www.cplusplus.com/reference/random/uniform_int_distribution/

For example, to get numbers in [1..100], one can write:
std::uniform_int_distribution<int> distribution( 1, 100 );


It is true that std::to_string() does create a string. However, if you will generate a lot of them, then you could do some caching:
1
2
3
4
5
6
7
8
std::array<std::string,100> names;
for ( size_t n=0; n < names.size(); ++n ) {
  names[n] = std::to_string( n+1 );
}
std::uniform_int_distribution<int> distribution( 0, names.size()-1 );

// in the loop
 s = names[ distribution(generator) ];
Last edited on
I am only creating one string at a time, and it is meant to be replaced by the new random number each time the loop iterates. There's a condition that stops the loop and prints out the string at that iteration.

I'll read the documentation you sent.

Thank you.

*edit after reading**

Okay, so I'm looking at something like this....

1
2
3
4
5
6
7
8

  std::default_random_engine generator;
  std::uniform_int_distribution<int> distribution(1,100);

  
  for (int i=0; i < MAX; ++i) {
   ranNum = distribution(generator);
   s = to_string(ranNum);


?
Last edited on
If you're just printing a number, you don't need to convert it to a string, cout << will do that for you. Just wanted to add that tidbit in.
Topic archived. No new replies allowed.