C Standard Library

C <stdlib.h> - atoi() Function



The C <stdlib.h> 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 as many characters as possible to form a valid integer number representation and converts them to an integer value. 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.

Syntax

int atoi (const char * str);

Parameters

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.

Example:

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

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

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 <stdlib.h> Library