C 標準庫提供多種字串轉數值函數,功能、錯誤處理、進制支援各有差異。本文整理 atof、atoi、atol、strtod、strtol、strtoul、gcvt、toascii、tolower、toupper 等函數原型、行為、回傳值、錯誤代碼與等效關係,供快速查閱。
| 函數 | 原型 | 說明 | 等效關係 |
|---|---|---|---|
atof | double atof(const char *nptr) | 跳過空白,解析浮點數(支援科學記號) | strtod(nptr, (char**)NULL) |
strtod | double strtod(const char *nptr, char **endptr) | 同 atof,若 endptr 不為 NULL 回傳結束位置 | — |
gcvt | char *gcvt(double number, size_t ndigits, char *buf) | 浮點數轉字串(四捨五入),含小數點/符號 | — |
| 函數 | 原型 | 說明 | 等效關係 |
|---|---|---|---|
atoi | int atoi(const char *nptr) | 轉換為 int | strtol(nptr, (char**)NULL, 10) |
atol | long atol(const char *nptr) | 轉換為 long | strtol(nptr, (char**)NULL, 10) |
strtol | long strtol(const char *nptr, char **endptr, int base) | 依 base (2–36 或 0) 轉長整數,支援 0x 前綴 | — |
strtoul | unsigned long strtoul(const char *nptr, char **endptr, int base) | 轉無號長整數,base 同 strtol | — |
atoi/atol/atof 無錯誤回傳(轉換失敗回 0/0.0,無法區分 "0" 與錯誤);strtol/strtoul/strtod 透過 endptr 與 errno(ERANGE)報告錯誤strtol/strtoul 支援 2–36 進制,base=0 時自動識別 0x (16進制)、0 (8進制)、其他 (10進制)strtol 溢位回傳 LONG_MAX/LONG_MIN 並設 errno=ERANGE;strtoul 回傳 ULONG_MAX| 函數 | 標頭檔 | 說明 |
|---|---|---|
toascii | <ctype.h> | 取字元低 7 位(第 8 位清零),轉為合法 ASCII |
tolower | <ctype.h> | 大寫轉小寫,非字母原樣回傳 |
toupper | <ctype.h> | 小寫轉大寫,非字母原樣回傳 |