-
Random Characters
There is probably a simple solution to this, but my mind is drawing a blank right now.
I know how to get a random letter...
srand( time(NULL) );
randChar = rand( ) % 26 + 'a';
I know how to get a random number...
srand( time(NULL) );
randNum = rand();
My question is..How do I get a random character so that the result can either be a letter OR a number??
-
look for a ascii table. it will tell you what numbers are actual key board characters. then use a couple ifs to parse it. if its ascii print it, if not get a new number.
-
something like this *might* work, but you'd need to be careful of numbering systems.
seed
loop of your choice
generate your random number
if(isalnum(random number))
do something
continue loop
-
0-9 is ASCII 48-57. a-z is ASCII 97-122.
Generate a random number 0-36, if it's 0-9 convert that to an ASCII 0-9 (add 48). If it's 10 or over add 87. The result should be a char of 0-9 or a-z.
-
/* No need for conditional tests, just initialise a char array with the values that you wish to use. No need to worry about ASCII codes. */
const char array[] = "abcdefghijklmnopqrstuvwxyz0123456789";
char RandChar;
srand(time(NULL));
/* Now use either of these two methods... */
RandChar = *(array + (rand() % (sizeof(array)-1)));
RandChar = array[rand() % (sizeof(array)-1)];
/* Use sizeof(array)-1 as sizeof() counts the terminating NULL as part of the array size. */