Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How would you create a random string of data 1

Status
Not open for further replies.

jdechirico

Programmer
Jul 11, 2006
13
US
I have a program that takes data entered from a keyboard and uses it as a random seed value, is there anyway to generate a string of up to 80 characters that could be used in place of data entered from a keyboard?
 
Use rand() to generate numbers between 0x30 & 0x7E, then cast them into char's...
 
cpjust,

any chance you could provide me with "code snippit" that would set a character field, randombytes, to a 80 byte random string?
 
I believe this should do it.
NOTE: Will only work on an ASCII system. EBCDIC or other systems will need a different method.
Code:
char RandomChar()
{
   return (char)((rand() % 78) + 30);
}


int main()
{
   char str[81];
   int i;

   srand(time());

   for ( i = 0; i < 80; ++i )
   {
      str[i] = RandomChar();
   }

   str[80] = '\0';

   return 0;
}
 
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char *rand_str(char *dst, int size)
{
   static const char text[] = "abcdefghijklmnopqrstuvwxyz"
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   int i, len = rand() % (size - 1);
   for ( i = 0; i < len; ++i )
   {
      dst[i] = text[rand() % (sizeof text - 1)];
   }
   dst[i] = '\0';
   return dst;
}

int main (void)
{
   char mytext[10];
   srand(time(0));
   puts(rand_str(mytext, sizeof mytext));
   puts(rand_str(mytext, sizeof mytext));
   puts(rand_str(mytext, sizeof mytext));
   return 0;
}

/* my output
fEKWZmOQ
IYF
NNabfD
*/
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top