atoi() — Convert Character String to Integer

Format

#include <stdlib.h>
int atoi(const char *string);

Language Level: ANSI

Threadsafe: Yes.

Locale Sensitive: The behavior of this function might be affected by the LC_CTYPE category of the current locale. For more information, see Understanding CCSIDs and Locales.

Description

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number. This character can be the null character that ends the string.

The atoi() function does not recognize decimal points or exponents. The string argument for this function has the form:

Read syntax diagramSkip visual syntax diagram>>-+------------+--+----+--digits------------------------------><
   '-whitespace-'  +-+--+
                   '- --'
 

where whitespace consists of the same characters for which the isspace() function is true, such as spaces and tabs. The atoi() function ignores leading white-space characters. The value digits represents one or more decimal digits.

Return Value

The atoi() function returns an int value that is produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type. The return value is undefined in the case of an overflow.

Example that uses atoi()

This example shows how to convert numbers that are stored as strings to numeric values.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
    int i;
    char *s;
 
    s = " -9885";
    i = atoi(s);     /* i = -9885 */
 
    printf("i = %d\n",i);
}
 
/*******************  Output should be similar to:  ***************
 
i = -9885
*/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]