Kumar Kumar - 2 months ago 17
C Question

print random string with skip some character in ascii

I have a problem on generating random string from a function. I have use for loop in this case. In below code I have used ascii characters from 65 to 90. But I also 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';

}


Please help me out

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;