c atoi function

When and how to use C atoi() library function in C?

The C library function atoi() is defined in the header file stdlib.h. It takes a string as an argument and returns an equivalent integer value. For example, the string “1234” will be converted to 1234.

When and why stores integer values as string?

Many times the input values are taken from a file or command lines arguments. We know those command-line arguments are the array of strings. An argument may be to use as an integer (e.g age), but as it’s in the string format while passing from command. So need a conversion to integer before use.

Example of converting a string to an integer.


        char str[10]  = "34679";
        printf(" For String = \"%s\", atoi() returns = %d\n",str,atoi(str));


For String = "34679", atoi() returns = 34679

How atoi() works?

prototype int atoi(const char *string)
Arguments –
string – Integer in string format (e.g “1025”).
Returns (int type) –
zero(0) – If can not convert the provided string to the integer. On success the equivalent integer value of the provided string.

What atoi() returns for an abnormal input?

A string is a combination of characters. Each character can be numeric, alpha, or special. The library function may also work on the string those have numbers and other characters. The return value depends on how the numeric characters are placed in the input argument.

  • If a string starts with a number, the return will be an integer till the consecutive numeric characters found. E.g for “23Cd67”, the return value is 23.
  • If the string starts with any character other than a number, the zero is returned. E.g “abc34!45” converted to zero.
  • If all characters are number conversion yield in an integer.

        char str1[10]  = "34abc!45";
        char str2[10]  = "abc34!45";
        char str3[10]  = "34567";
        printf(" For String = %s, conversion to integer returns = %d\n",str1,atoi(str1));
        printf(" For String = %s, conversion to integer returns = %d\n",str2,atoi(str2));
        printf(" For String = %s, conversion to integer returns = %d\n",str3,atoi(str3));


For String = 34abc!45, conversion to integer returns = 34
For String = abc34!45, conversion to integer returns = 0
For String = 34567, conversion to integer returns = 34567