Search code examples
c++catoi

What is actually going on with atoi in this situation?


I'm relatively new to C and I'm curious why I'm having problems with atoi in this situation. I feel like I am not understanding something fundamental. Here is my sample code:

int main()
{
    char last[3];
    last[2]='\0';
    uint16_t num1;
    uint16_t num2;

    // I read in num1 and num2 from a file and do an integer operation on them. bigarray is the file contents. bigarray[i] is a integer
    num1=bigarray[i] - 1;
    num2=bigarray[i+1] - 1;
    last[0]=(char)num1;
    last[1]=(char)num2;
    printf("%i\n:", atoi(last));
}

When I print out last[0] and last[1] seperatly it gives me the correct values. When I print out atoi(last) then it gives me 0.

Why does atoi give me 0 in this situation, and how can I fix it?


Solution

  • atoi expects ASCII characters, so if the array is, let's say last[0] = 1 and last[1] = 2, it will find no characters, if it was last[0] = '1' and last[1] = '2' than it would print 12.

    In this particular case you can achieve that by:

    last[0]='0' + num1;
    last[1]='0' + num2;
    

    (assuming num1 and num2 are between 0-9)

    Short edit to explain the idea:

    The ascii values of the digits '0'(0x30) to '9'(0x39) are sequential, so adding 0 to '0' (0x30) will give you '0'(0x30) and adding 2 to '0'(0x30) will give you '2'(0x32)