Thread: Random Characters

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    25

    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??

  2. #2
    Registered User
    Join Date
    Jul 2002
    Posts
    913
    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.

  3. #3
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    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
    I haven't used a compiler in ages, so please be gentle as I try to reacclimate myself. :P

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    32
    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.
    - Tigs

  5. #5
    Registered User
    Join Date
    Feb 2003
    Posts
    8
    /* 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. */
    Last edited by Heraclitus; 03-09-2003 at 02:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Counting the characters from each word from a text file
    By flipguy_ph in forum C Programming
    Replies: 6
    Last Post: 04-27-2009, 05:56 PM
  2. problem with reading characters
    By csvraju in forum C Programming
    Replies: 4
    Last Post: 03-31-2009, 07:59 AM
  3. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 07:35 AM
  4. Random word problem
    By goron350 in forum C++ Programming
    Replies: 2
    Last Post: 05-14-2005, 03:44 PM
  5. Question for Random class
    By joenching in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2005, 11:22 PM