How to convert a number between 0-9 to Char

Discussion in 'C' started by Musab, Jul 14, 2008.

  1. Musab

    Musab New Member

    Joined:
    Jul 1, 2008
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Hello again :)

    I'm generating a random number between 0 and 9
    I want to assign that number to a character so I can store it in a character array;

    something like
    if i = 3
    c = '3';

    if i =4
    c = '4'

    but smarter way :sosp:
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Directly assigning should do the job for you.

    char c = i;
     
  3. akhanna01

    akhanna01 New Member

    Joined:
    Jul 12, 2008
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    add the ascii value to it................
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    if (i>=0 && i<=9) c=i+'0';
    Or just generate random numbers between '0' and '9'.
     
  5. Musab

    Musab New Member

    Joined:
    Jul 1, 2008
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    Thanks for the tip...yes rand()%10 + '0' works
     
  6. aali

    aali New Member

    Joined:
    Jul 16, 2008
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Location:
    Riyadh
    use dynamic cast
    or
    for example
    int a;
    char b;
    b<int>=a;
     
  7. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    yes, but will that convert 0x00000000 to '0', which is what the OP wanted, or will it convert it to 0x00?
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice