Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

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()?
0
ennkay
Asked:
ennkay
1 Solution
 
mnashadkaCommented:
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';
}
0
 
ennkayAuthor Commented:
mnashadka
Looks good but i can't use std::string. Can you modify the code using a char array?
0
 
happylinCommented:
// 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');
 }
}
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
zebadaCommented:
mnashadka should still get the points but here's the C version...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{
  char *c,s[8];
  int  i,n;
 
  srand(time(0));
  for ( c=s,i=0 ; i<7 ; i++,c++ ) {
    n = rand() % 36;
    if ( n<26 )
      *c = n+'a';
    else
      *c = (n-26) + '0';
  }
  *c = '\0';
  printf("%s\n",s);
}
0
 
zebadaCommented:
happylin - you beat me by one minute - that's close
0
 
ennkayAuthor Commented:
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?

0
 
zebadaCommented:
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.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now