Converts a string to an integer.
Include
<stdlib.h>
Prototype
int atoi(const char *s);
Argument
s
Return Value
Returns the converted integer if successful; otherwise, returns 0.
Remarks
The number may consist of the following:
[whitespace] [sign] digits
Optional whitespace followed by an optional sign, then a sequence of one or more digits.
The conversion stops when the first unrecognized character is reached. The conversion is
equivalent to (int) strtol(s,0,10)
, except it does no error checking so
errno
will not be set.
Example
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char a[] = " -127";
char b[] = "Number1";
int x;
x = atoi(a);
printf("String = \"%s\"\tint = %d\n", a, x);
x = atoi(b);
printf("String = \"%s\"\tint = %d\n", b, x);
}
Example Output
String = " -127" int = -127
String = "Number1" int = 0