Kumar Kumar - 2 months ago 21
C Question

Print a random string

I have a problem generating a random string in a function.

In the code below I have used ASCII characters from 65 to 90. I want to include 48 to 57, skipping 58 to 64.

Is there any way to do this?

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

int main()
{
char s[30];
random_string(s, 6,65,90);
printf("\n%s\n", s);
return 0;
}

void random_string(char * string, unsigned length,int min,int max)
{
/* Seed number for rand() */
srand((unsigned int) time(0) + getpid());

/* ASCII characters 33 to 126 */
unsigned int num_chars = length - 1;
unsigned int i;
for (i = 0; i < num_chars; ++i)
{
string[i] = rand() % (max - min + 1) + min;
}

string[num_chars] = '\0';
}

Answer

I think that simplest way to achieve that is to reroll rand() if you have got number in unwanted range. To specify desired range, you can use bitmask or bool array instead of min/max.

It will look something like this:

do { c = rand() % 256; } while (!desired[c]);
string[i] = c;
Comments