複製鏈接
請複製以下鏈接發送給好友

strtol

鎖定
strtol函數會將參數nptr字符串根據參數base來轉換成長整型數,參數base範圍從2至36,或0。
中文名
strtol
概    述
strtol函數會將參數np
函數説明
參數base範圍從2至36
使用學科
C語言

strtol函數定義

long int strtol(const char *nptr,char **endptr,int base);

strtol函數説明

參數base代表採用的進制方式,如base值為10則採用10進制,若base值為16則採用16進制等。當base值為0時則是採用10進製做轉換,但遇到如’0x’前置字符則會使用16進製做轉換、遇到’0’前置字符而不是’0x’的時候會使用8進製做轉換。
一開始strtol()會掃描參數nptr字符串,跳過前面的空格字符,直到遇上數字或正負符號才開始做轉換,再遇到非數字或字符串結束時('\0')結束轉換,並將轉換數值返回。參數endptr指向停止轉換的位置,若字符串nptr的所有字符都成功轉換成數字則endptr指向串結束符'\0'。判斷是否轉換成功,應檢查**endptr是否為'\0'。

strtol主要特點

1.不僅可以識別十進制整數,還可以識別其它進制的整數,取決於base參數,比如strtol("0XDEADbeE~~", NULL, 16)返回0xdeadbee的值,strtol("0777~~", NULL, 8)返回0777的值。
2.endptr是一個傳出參數,函數返回時指向後面未被識別的第一個字符。例如char *pos; strtol("123abc", &pos, 10);,strtol返回123,pos指向字符串中的字母a。如果字符串開頭沒有可識別的整數,例如char *pos; strtol("ABCabc", &pos, 10);,則strtol返回0,pos指向字符串開頭,可以據此判斷這種出錯的情況,而這是atoi處理不了的。
3.如果字符串中的整數值超出long int的表示範圍(上溢或下溢),則strtol返回它所能表示的最大(或最小)整數,並設置errno為ERANGE,例如strtol("0XDEADbeef~~", NULL, 16)返回0x7fffffff並設置errno為ERANGE

strtol使用範例

#include<stdlib.h>
#include<stdio.h>
int main()
{
    char *string, *stopstring;
    double x;
    int base;
    long l;
    unsigned long ul;
    string = "3.1415926 This stopped it";
    x = strtod(string, &stopstring);
    printf("string = %s\n", string);
    printf("strtod = %f\n", x);
    printf("Stopped scan at: %s\n", stopstring);
    string = "-1011 This stopped it";
    l = strtol(string, &stopstring, 10);
    printf("string = %s\n", string);
    printf("strtol = %ld\n", l);
    printf("Stopped scan at: %s\n", stopstring);
    string = "10110134932";
    printf("string = %s\n", string);
    /*Convertstringusingbase2,4,and8:*/
    for(base = 2; base <= 8; base *= 2)
    {
        /*Convertthestring:*/
        ul = strtoul(string, &stopstring, base);
        printf("strtol = %ld(base %d)\n", ul, base);
        printf("Stopped scan at: %s\n", stopstring);
    }
    return 0;
}
輸出結果:
string = 3.1415926 This stopped it
strtod = 3.141593
Stopped scan at:  This stopped it
string = -1011 This stopped it
strtol = -1011
Stopped scan at:  This stopped it
string = 10110134932
strtol = 45(base 2)
Stopped scan at: 34932
strtol = 4423(base 4)
Stopped scan at: 4932
strtol = 2134108(base 8)
Stopped scan at: 932