atoi、atol 只支援十進制且無錯誤回報。strtol 是功能最完整的字串轉長整數函數:
0x/0 前綴)endptr 回報解析停止位置,可偵測無效字元errno = ERANGE 並回傳 LONG_MAX/MIN#include <stdlib.h> long int strtol(const char *nptr, char **endptr, int base);
| 參數 | 說明 |
|---|---|
nptr | 待轉換字串,前導空白會被跳過 |
endptr | 非 NULL 時,回傳第一個無效字元位址 |
base | 進制(2~36 或 0)。0 表示自動偵測:0x→16、0→8、其他→10 |
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main()
{
char a[] = "100";
char b[] = "100";
char c[] = "0x11";
char d[] = " -123abc";
char *pos;
long x, y, z, w;
x = strtol(a, NULL, 10); // 十進制 100
y = strtol(b, NULL, 2); // 二進制 100 → 4
z = strtol(c, NULL, 16); // 十六進制 0x11 → 17
w = strtol(d, &pos, 10); // -123,pos 指向 'a'
printf("x=%ld, y=%ld, z=%ld, w=%ld\n", x, y, z, w);
printf("剩餘字串: \"%s\"\n", pos);
// 錯誤檢查範例
errno = 0;
long val = strtol("9999999999999999999", NULL, 10);
if (errno == ERANGE) printf("溢位!\n");
return 0;
}
輸出:
x=100, y=4, z=17, w=-123 剩餘字串: "abc"
| 特性 | atoi | strtol |
|---|---|---|
| 進制支援 | 僅 10 進制 | 2~36 進制 + 自動偵測 |
| 錯誤回報 | 無(返回 0 無法區分 "0" 與 "abc") | endptr + errno |
| 溢位處理 | 未定義行為 | 飽和至 LONG_MAX/MIN + ERANGE |
| 尾隨字元 | 忽略 | 透過 endptr 精確定位 |
strtoul:轉 unsigned longstrtoll / strtoull:C99,轉 64 位元 long longstrtof / strtod / strtold:浮點數轉換