Search code examples
catoi

Why is ATOI returning a 0 in this code?


I'm just getting started out with C and I'm trying to learn the ATOL function. Can someone tell me why it keeps printing a 0? I know that means that the conversion can't be performed, but I'm not sure why.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int i = atoi ("  bl149");
    printf("%d\n", i);  
    return 0;
}

Solution

  • atoi basically convert a string having a number in to integer one and whatever it will convert that will become the return value for it. OR to be more precise atoi function start checking from the beginning of string. if it has digit(from the begining only) then it will return that value in integer. Below example will clear the concept For example

    atoi("1234") 
    --> it will convert string "1234" in to integer and return it 
             --> i.e. ouput is 1234
    atoi("1234abcd") --> i.e. ouput is 1234
    atoi("a1234abcd") --> i.e. ouput is 0   
    

    In your case since your string starting from b (" b1149") so it will return 0