Search code examples
carraysatoi

Converting char array to atoi is failing


I've checked other posts related to this subject and have used the atoi function to convert a string, but the value is always 0.

Here are the values stored in hold4:

char hold4[4] = { "0", "." , "1", "5", "\0");

I then attempt to convert to an int and I get

int hm = atoi(hold4);

hm prints out as:

hm = 0 

I expect hm to be 0.15, as that's the value in hold4. I want to use this value for subsequent math operations.

Here is my code:

int x = 0;
int pixel = 0;  
char hold[10];
char hold4[4];  

for(x=0; x < linesCount; x++)
{
    fscanf(model, "%c", &hold[x]);
    if(hold[x] == '\0' || hold[x] == '\r' || hold[x] == '\n')
    {
        hold4[0] = hold[x-4]; 
        hold4[1] = hold[x-3]; 
        hold4[2] = hold[x-2]; 
        hold4[3] = hold[x-1];
        hold4[4] = '\0'; 
    //  printf("new line: break\n");
    }
    //printf("pixel: %c\n", hold[x]);
}

int hm = atoi(hold4);

printf("\nhold4: %d\n", hm);

How do I make this work?


Solution

  • You are missing the whole point of integer. Integer is a whole number (1, 2, 3, 4...) and can't have decimal points. What you are looking for is float/double.

    Try with this: atof()