Share via


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 值。 如果輸入無法轉換成該類型的值,則傳回值是 0Latol

如果這些函式溢位具有大正整數值,則會傳回 LONG_MAX。 如果函式溢位具有大負整數值, LONG_MIN 則會傳回 。 在所有超出範圍的情況下,errno 設為 ERANGE。 如果傳入的參數為 NULL,則會叫用無效的參數處理程式,如參數驗證中所述。 如果允許繼續執行,這些函式會將 errno 設為 EINVAL,並傳回 0。

備註

這些函式會將字元字串轉換成長整數值 (atol)。

輸入字串是一串字元,可解譯為所指定類型的數值。 函式會在無法辨識為數位一部分的第一個字元停止讀取輸入字串。 此字元可能是終止字串的 Null 字元 (\0L\0)。

atolstr 引數具有下列形式:

[] [whitespacesign] [] [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