需要把字串形式的數字轉成浮點數時,strtof 與 strtod 是最直接的選擇。以下是一份可直接編譯執行的範例。
// file: a.cpp
#include <stdio.h>
#include <stdlib.h>
int main() {
char szOrbits[] = "365.24";
char* pEnd;
float f1;
f1 = strtof(szOrbits, &pEnd);
printf("%f\n", f1);
return 0;
}
編譯與執行:
$ g++ a.cpp -o aaa
$ ./aaa
365.239990
輸出成 365.239990 而非 365.24,是因為 float 只有約 7 位有效數字,二進位浮點無法精確表示這個小數——這不是 bug,若要求精度請改用 double 並搭配 strtod。
在 Linux 上執行 man strtod 即可查到:
NAME
strtod, strtof, strtold - convert ASCII string to floating point number
SYNOPSIS
#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
#define _XOPEN_SOURCE=600 /* or #define _ISOC99_SOURCE */
#include <stdlib.h>
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
DESCRIPTION
The strtod(), strtof(), and strtold() functions convert the initial
portion of the string pointed to by nptr to double, float, and
long double representation, respectively.
nptr:要轉換的字串指標。函式會跳過前導空白,並在遇到第一個非法字元時停止。endptr:可選的輸出參數,回傳「停止解析的位置」。若傳入 NULL 就忽略。實務上很值得用它來驗證輸入是否合法:檢查 endptr == nptr 代表完全沒有轉到任何數字,*endptr != '\0' 代表後面還有殘留字元。另外這組函式在溢位時會回傳 HUGE_VAL / HUGE_VALL 並設定 errno = ERANGE,下溢則回傳接近零的值。若要嚴格處理使用者輸入,這些都該一併檢查,而不是只把 atof() 的結果直接拿去用——atof 正是無法回報錯誤的那個版本。