atol, _atol_l, _wtol, _wtol_l

将字符串转换为长整型。

语法

long atol(
   const char *str
);
long _atol_l(
   const char *str,
   _locale_t locale
);
long _wtol(
   const wchar_t *str
);
long _wtol_l(
   const wchar_t *str,
   _locale_t locale
);

参数

str
要转换的字符串。

locale
要使用的区域设置。

返回值

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

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

备注

这些函数将字符串转换为长整型值 (atol)。

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

atolstr 参数具有以下形式:

[whitespace] [sign] [digits]

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

_wtolatol 相同,但前者采用宽字符串。

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

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

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tstol atol atol _wtol
_ttol atol atol _wtol

要求

例程 必需的标头
atol <stdlib.h>
_atol_l, _wtol, _wtol_l <stdlib.h><wchar.h>

示例

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

// crt_atol.c
// This program shows how numbers stored as
// strings can be converted to numeric values
// using the atol functions.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

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

    // An example of the atol function
    // with leading and trailing white spaces.
    str = "  -2309 ";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // Another example of the atol function
    // with an arbitrary decimal point.
    str = "314127.64";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

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

另请参阅

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