6.19.10 atoi Function
Converts a string to an integer.
Include
<stdlib.h>
Prototype
int atoi(const char *s);
Argument
s
- string to be converted
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
See the notes at the beginning of this chapter or section for
information on using printf()
or scanf()
(and other functions reading and writing the stdin
or
stdout
streams) in the example code.
#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