the rand() function and strings

Nov 4, 2013 at 12:35am
I am looking at this piece of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
 
using namespace std;
 
int main()
{
    srand(time(0)); // seed random number generator
 
    string sString; // length 0
    sString.reserve(64); // reserve 64 characters
 
    // Fill string up with random lower case characters
    for (int nCount=0; nCount < 64; ++nCount)
        sString += 'a' + rand() % 26;
 
    cout << sString;
}


I'm confused about this part right here:
'a' + rand() % 26

The rand() function returns an integral number in the range between 0 and RAND_MAX. I assume RAND_MAX here is 26. And this is randomly return one of the 26 letters of the alphabet. But what is the point of the 'a' here?
Nov 4, 2013 at 12:39am
If I want a random number between 5 and 10, then that means that 5 is the minimum, and 10 the maximum.

Therefore:
5 + (rand()%10)

In ascii, 'a' is 97 in decimal.
The purpose of the 'a' in this case, is to create a random number and then add 'a'(97), the minimum, to it. Otherwise, you'd be creating characters from 0-25
Nov 4, 2013 at 12:58am
@xismn your formula will never generate the number 10.
Nov 4, 2013 at 1:29am
To generate a random number in a range the formula is:
rand() % ( max - min + 1 ) + min;
Nov 4, 2013 at 3:26am
Seriously, I'm on a roll today. Let's just pretend I said "exclusive"...
Topic archived. No new replies allowed.