atoi, _atoi_l, _wtoi, _wtoi_l
0x01.原型
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
);
Parameters
str
要转换的字符串。
locale
要使用的区域设置。
0x02.返回值
每个函数返回通过将输入字符解释为数字而产生的int值。如果输入无法转换为该类型的值,则atoi和_wtoi的返回值为0。
在具有大的负整数值的溢出的情况下,返回LONG_MIN。 atoi和_wtoi在这些条件上返回INT_MAX和INT_MIN。在所有超出范围的情况下,errno设置为ERANGE。如果传入的参数为NULL,则调用无效参数处理程序,如参数验证中所述。如果允许继续执行,这些函数将errno设置为EINVAL并返回0。
0x03.备注
这些函数将字符串转换为整数值(atoi和_wtoi)。 输入字符串是一系列字符,可以解释为指定类型的数值。 该函数停止读取作为数字一部分无法识别的第一个字符处的输入字符串。 此字符可以是终止字符串的空字符(’\ 0’或L’\ 0’)。
atoi
and _wtoi
的str参数具有以下形式:
[whitespace] [sign] [digits]]
空格由空格或制表符字符组成,被忽略; 符号是加号(+)或减号( - ); 并且数字是一个或多个数字。
带有_l后缀的这些函数的版本是完全相同的,除了它们使用传入的locale参数而不是当前语言环境。 有关详细信息,请参阅区域设置。
0x04.Example
// 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 occuring.
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.