ctoi?

This is a discussion on ctoi? within the C++ Programming forums, part of the General Programming Boards category; hi, just wondering is there a function that converts a single char to an int. The parameter being passed needs ...

  1. #1
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359

    ctoi?

    hi, just wondering is there a function that converts a single char to an int. The parameter being passed needs to be a char as well, thanks.
    Be a leader and not a follower.

  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    151
    atoi(). Pass the address of a char.

  3. #3
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    I've tried atoi but it will only allow strings as the parameter,
    Be a leader and not a follower.

  4. #4
    Registered User dirkduck's Avatar
    Join Date
    Aug 2001
    Posts
    428
    Just throwing a guess in the air, maybe you could typecast it: num=atoi((char*)yourchar). If all else fails, you could put the char into a string then use that.

  5. #5
    Registered User
    Join Date
    Jun 2002
    Posts
    151
    It 'only' allows strings because it's expecting the start address of a string. Just pass the address of a char.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    atoi() will only accept strings. This is by design.

    Code:
    int ctoi( int c )
    {
        return c - '0';
    }
    Use that.

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Soz for the late reply but i've been working at late, would you be able to explain how the following code works, thanks.

    Code:
    return c - '0'
    Be a leader and not a follower.

  8. #8
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Figured it out, the ascii val to '0' is 48, therefore the code is basically subtracting 48 from the argument passed due to the int return type. Ascii code for '3' is 51, so 51 - 48 is (3).
    Be a leader and not a follower.

  9. #9
    Registered User toaster's Avatar
    Join Date
    Apr 2002
    Posts
    161
    why not try casting?

    Code:
    ...
    unsigned char x= '?';
    cout<<int(x);
    ...

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21