C語言中如何將字符串轉換成float和double類型
先貼上可編譯運行的源代碼:
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;
}
執行結果:
[tuxedo@imorcl yali_test]$ g++ a.cpp -o aaa
[tuxedo@imorcl yali_test]$ ./aaa
365.239990
man參考手冊:在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.
。。。