C Data Type Functions - C atoi






Accepts +-0123456789 leading blanks and converts to integer.

int atoi(const char *str );

The string str is converted to an integer (type int).

Any initial whitespace characters are skipped.

The number may consist of an optional sign and a string of digits.

Conversion stops when the first unrecognized character is reached.

Prototype

int atoi (const char * str);

Parameter

This function has the following parameter.

str
C-string beginning with the representation of an integral number.

Return

The function returns the converted integral number as an int value.

If the converted value would be out of the range of representable values by an int, it causes undefined behavior.





Example


#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
/*from   ww  w .j a  v  a  2 s .  c o m*/
int main ()
{
  int i;
  char buffer[256];
  printf ("Enter a number: ");
  fgets (buffer, 256, stdin);
  i = atoi (buffer);
  printf ("The value entered is %d. Its double is %d.\n",i,i*2);
  return 0;
} 

       

The code above generates the following result.





Example 2


#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    printf("%i\n", atoi(" -123junk"));
}

The code above generates the following result.