Link to home
Start Free TrialLog in
Avatar of ennkay
ennkay

asked on

Random string generation using rand()

I want to create a string of seven random characters containing a combination of small letters a-z and numbers 0-9. e.g. "w4dg7hg" or "3ghtry8".
Can anyone please give me the code for this using rand()?
Avatar of mnashadka
mnashadka

std::string s;
for(int i = 0; i < 7; ++i)
{
  int number = rand() % 36;
  if(number < 26)
    s += (number + 'a');
  else
    s += ((number - 26) + '0';
}
Avatar of ennkay

ASKER

mnashadka
Looks good but i can't use std::string. Can you modify the code using a char array?
// note a_nSize is buffer size of o_zStr include NULL character
void RandomString(char* o_zStr,const int a_nSize)
{
 o_zStr[a_nSize-1]=NULL;
 int nNumber;
 for( int i = 0 ; i < a_nSize-1 )
 {
  nNumber=rand()%36;
  if( nNumber < 26  )
   o_zStr[i]=(nNumber+'a');
  else
   o_zStr[i]=(nNumber-26+'0');
 }
}
ASKER CERTIFIED SOLUTION
Avatar of zebada
zebada

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
happylin - you beat me by one minute - that's close
Avatar of ennkay

ASKER

zebada
I have accepted your answer since it plugs in better in my code. A couple of question:
Why time(0) for random seed?
What does rand()%36 mean?

time(0) will return a different value each time it is called - therefore the random number generator will return a different sequence of random numbers each time the program is run. Although looking at the documentation any value other than 1 will do the same thing. So I guess srand(2) would be just as effective as srand(time(NULL)). I just never read the doco carefully before.

rand() will return a number between 0 and RAND_MAX. The modulus operator % will give us the remained of the random value when divided by 36 which in effect converts the range of values to 0..35 which is the same as the number of alpahnumeric characters that you wanted to use for your string.