atoi, _atoi_l, _wtoi, _wtoi_l

将字符串转换为整数。

语法

int atoi(
   const char *str
);
int _wtoi(
   const wchar_t *str
);
int _atoi_l(
   const char *str,
   _locale_t locale
);
int _wtoi_l(
   const wchar_t *str,
   _locale_t locale
);

参数

str
要转换的字符串。

locale
要使用的区域设置。

返回值

每个函数均返回 int 值,此值是通过将输入字符解释为数字来生成的。 如果输入不能转换为该类型的值,则 atoi_wtoi 的返回值为 0。

当函数溢出大负整数值时,将返回 LONG_MIN。 在这些情况下,atoi_wtoi 返回 INT_MAXINT_MIN。 在所有超出范围的情况下,将 errno 设置为 ERANGE。 如果传入的参数为 NULL,则调用无效参数处理程序,如参数验证中所述。 如果允许执行继续,则这些功能将 errno 设置为 EINVAL,并返回 0。

备注

这些函数将字符串转换为整数值(atoi_wtoi)。 输入字符串是一系列字符,可以解释为指定类型的数值。 该函数在首个它无法识别为数字组成部分的字符处停止读取输入字符串。 此字符可能是终止字符串的空字符('\0' 或 L'\0')。

atoi_wtoistr 参数采用以下格式:

[whitespace] [sign] [digits]

whitespace 由空格或制表符组成,可被忽略;sign是加号 (+) 或减号 (-);digits 是一个或多个数字。

这些带有 _l 后缀的函数的版本相同,只不过它们使用传递的区域设置参数而不是当前区域设置。 有关详细信息,请参阅 Locale

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tstoi atoi atoi _wtoi
_ttoi atoi atoi _wtoi

要求

例程 必需的标头
atoi <stdlib.h>
_atoi_l, _wtoi, _wtoi_l <stdlib.h><wchar.h>

示例

此程序说明如何使用 atoi 函数将存储为字符串的数字转换为数值。

// crt_atoi.c
// This program shows how numbers
// stored as strings can be converted to
// numeric values using the atoi functions.

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

int main( void )
{
    char    *str = NULL;
    int     value = 0;

    // An example of the atoi function.
    str = "  -2309 ";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );

    // Another example of the atoi function.
    str = "31412764";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );

    // Another example of the atoi function
    // with an overflow condition occurring.
    str = "3336402735171707160320";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );
    if (errno == ERANGE)
    {
       printf("Overflow condition occurred.\n");
    }
}
Function: atoi( "  -2309 " ) = -2309
Function: atoi( "31412764" ) = 31412764
Function: atoi( "3336402735171707160320" ) = 2147483647
Overflow condition occurred.

另请参阅

数据转换
数学和浮点支持
区域设置
_ecvt
_fcvt
_gcvt
setlocale_wsetlocale
_atodbl_atodbl_l_atoldbl_atoldbl_l_atoflt_atoflt_l