Thread: Generating Random characters/numbers

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    6

    Generating Random characters/numbers

    Hi
    Does any know if there is any code i can use to generate random letters or numbers?

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Check the FAQ.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Generally, you can use rand() to generate random numbers. You can then use modulo and addition to make it the range you want.

    Generically:
    Code:
    int x = rand() % (1 + max - min) + min;
    Of course for digits, this can be simplified:
    Code:
    char ch = rand() % 10 + '0';
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    6
    thanks guys i got some info on the numbers.

    Any ideas for characters?

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by milanbarosh View Post
    thanks guys i got some info on the numbers.

    Any ideas for characters?
    You should be able to use my generic code, and just substitute as needed with the constants that apply to the character set you want to use (presumably 'a'-'z' or 'A'-'Z', but by no means guaranteed).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    For a guarenteed character range, you could create use a string with an acceptable alphabet, and then use the random number as an index.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generating random letters
    By ominub in forum C Programming
    Replies: 6
    Last Post: 04-29-2009, 01:12 AM
  2. Generating random 2D mountains/terrain
    By Flaug in forum C++ Programming
    Replies: 7
    Last Post: 04-12-2009, 02:49 PM
  3. Generating a random number?
    By Konspiracy in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 12:33 AM
  4. Help generating multiple random numbers
    By d-dub in forum C++ Programming
    Replies: 7
    Last Post: 10-30-2006, 01:00 PM
  5. Replies: 7
    Last Post: 09-26-2005, 05:09 PM