Share via


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

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

備註

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

atoi_wtoistr 引數具有下列形式:

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