C++ Standard Library C++ STL Library

C++ <cstdlib> - atoi() Function

The C++ <cstdlib> atoi() function is used to interpret an integer value in a byte string pointed to by str.

The function first discards any whitespace characters until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by numeric digits. The string may contain additional characters after those that form the integral number, which are ignored.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists (because either empty or contains only whitespaces), no conversion is performed and zero is returned.


int atoi (const char * str);


str Specify pointer to the null-terminated byte string to be interpreted.

Return Value

On success, the function returns the converted integral number as an int value. If no conversion can be performed, 0 is returned. If the converted value falls out of the range of int type, the return value is undefined.


The example below shows the usage of <cstdlib> atoi() function.

#include <cstdio>
#include <cstdlib>

int main (){
  char str1[] = "123";
  char str2[] = "10.55";
  char str3[] = "100 some words";
  char str4[] = "some words 555";

  int num1 = atoi(str1);
  int num2 = atoi(str2);
  int num3 = atoi(str3);
  int num4 = atoi(str4);

  //displaying the result
  printf("atoi(\"%s\") = %d\n", str1, num1);
  printf("atoi(\"%s\") = %d\n", str2, num2);
  printf("atoi(\"%s\") = %d\n", str3, num3);
  printf("atoi(\"%s\") = %d\n", str4, num4);

  return 0;

The output of the above code will be:

atoi("123") = 123
atoi("10.55") = 10
atoi("100 some words") = 100
atoi("some words 555") = 0

❮ C++ <cstdlib> Library