ASCII To Integer – atoi in C

If you have ever had to read input from a command line into your C program you may have stumbled across the atoi function, especially if you were reading numeric input. Perhaps you have a file that contains a set of stock data that needs to be converted to integeres. To interpret and use the values you have to convert it from its ASCII representation to its integer equivalent. Only languages that deal in types have to deal with these conversions, yay C! Luckily there are built-in functions like atoi to use.

atoi or Ascii to Integer can be found within the stdlib.h header file. Its prototype is:

#include <stdlib.h>
 
int atoi(const char *nptr);

The atoi function simply takes a character array/pointer and returns the converted value, this value can then be stored as an integer and off you go. Lets look at an example:

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
  char *str = "6543";
  char *str2 = "123erik";
 
  fprintf(stdout, "The string %s as an integer is = %d\n",str,atoi(str));
  fprintf(stdout, "The string %s as an integer is = %d\n",str2,atoi(str2));
 
  return 0;
}
---- Output ----
The string 6543 as an integer is = 6543
The string 123erik as an integer is = 123

Notice in the example I am using %d to print a decimal value, which works fine as the return value of atoi is an integer.

atoi Limitations

  1. atoi is not thread-safe. This means that two threads could not call atoi simultaneously.
  2. atoi does not permit asynchronous calls on some operating systems.
  3. atoi will only convert from base 10 ASCII to integer.
  4. atoi is actually deprecated and strtol should be used in its place.
  5. atoi will not set errno on error.

It is now suggested that during conversion the strtol (string to long) function should be used. It can convert the string to any base from 2 to 36 inclusive, errno is set on error to detect problems with its return values. I will look at strtol in more detail in my next post. If you just need a quick conversion from ASCII to integer atoi, however, may be your way to go.