long int strtol(const char *nptr,char **endptr,int base);函數
這個函數會將參數nptr字符串根據參數base來轉換成長整型數。參數base範圍從2至36,或0。參數base表明採用的進制方式,如base值爲10則採用10進制,若base值爲16則採用16進制等。當base值爲0時則是採用10進製作轉換,但遇到如’0x’前置字符則會使用16進製作轉換、遇到’0’前置字符而不是’0x’的時候會使用8進製作轉換。spa
一開始strtol()會掃描參數nptr字符串,跳過前面的空格字符,直到趕上數字或正負符號纔開始作轉換,再遇到非數字或字符串結束時('\0')結束轉換,並將結果返回。若參數endptr不爲NULL,則會將遇到不合條件而終止的nptr中的字符指針由endptr返回;若參數endptr爲NULL,則會不返回非法字符串。指針
不只能夠識別十進制整數,還能夠識別其它進制的整數,取決於base參數,好比strtol("0XDEADbeE~~", NULL, 16)返回0xdeadbee的值,strtol("0777~~", NULL, 8)返回0777的值。code
endptr是一個傳出參數,函數返回時指向後面未被識別的第一個字符。例如char *pos; strtol("123abc", &pos, 10);,strtol返回123,pos指向字符串中的字母a。若是字符串開頭沒有可識別的整數,例如char *pos; strtol("ABCabc", &pos, 10);,則strtol返回0,pos指向字符串開頭,能夠據此判斷這種出錯的狀況,而這是atoi處理不了的。字符串
若是字符串中的整數值超出long int的表示範圍(上溢或下溢),則strtol返回它所能表示的最大(或最小)整數,並設置errno爲ERANGE,例如strtol("0XDEADbeef~~", NULL, 16)返回0x7fffffff並設置errno爲ERANGEstring
#include <stdlib.h> #include <stdio.h> void main( void ) { char *string, *stopstring; double x; int base; long l; unsigned long ul; string = "3.1415926This stopped it"; x = strtod( string, &stopstring ); printf( "string = %s\n", string ); printf(" strtod = %f\n", x ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "-10110134932This stopped it"; l = strtol( string, &stopstring, 10 ); printf( "string = %s", string ); printf(" strtol = %ld", l ); printf(" Stopped scan at: %s", stopstring ); string = "10110134932"; printf( "string = %s\n", string ); /* Convert string using base 2, 4, and 8: */ for( base = 2; base <= 8; base *= 2 ) { /* Convert the string: */ ul = strtoul( string, &stopstring, base ); printf( " strtol = %ld (base %d)\n", ul, base ); printf( " Stopped scan at: %s\n", stopstring ); } } 輸出結果: string = 3.1415926This stopped it strtod = 3.141593 Stopped scan at: This stopped it string = -10110134932This stopped it strtol = -2147483648 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