Choreonoid  1.8
strtofloat.h
Go to the documentation of this file.
1 #ifndef CNOID_UTIL_STRTOF_H
2 #define CNOID_UTIL_STRTOF_H
3 
4 // Replacement for 'strtod()' function in Visual C++
5 // This is neccessary because the implementation of VC++6.0 uses 'strlen()' in the function,
6 // so that it becomes too slow for a string buffer which has long length.
7 
8 #ifndef _MSC_VER
9 #include <cstdlib>
10 #endif
11 
12 namespace cnoid {
13 
14 #ifndef _MSC_VER
15 
16 inline float strtof(const char* nptr, char** endptr){
17  return std::strtof(nptr, endptr);
18 }
19 inline double strtod(const char* nptr, char** endptr){
20  return std::strtod(nptr, endptr);
21 }
22 
23 #else
24 
25 template<typename T> T strtofloat(const char* nptr, char** endptr)
26 {
27  const char* org = nptr;
28  bool valid = false;
29  T value = 0.0;
30  T sign = +1.0;
31 
32  if(*nptr == '+'){
33  nptr++;
34  } else if(*nptr == '-'){
35  sign = -1.0;
36  nptr++;
37  }
38  if(isdigit((unsigned char)*nptr)){
39  valid = true;
40  do {
41  value = value * 10.0 + (*nptr - '0');
42  nptr++;
43  } while(isdigit((unsigned char)*nptr));
44  }
45  if(*nptr == '.'){
46  //valid = false; // allow values which end with '.'. For example, "0."
47  nptr++;
48  if(isdigit((unsigned char)*nptr)){
49  T small = 0.1;
50  valid = true;
51  do {
52  value += small * (*nptr - '0');
53  small *= 0.1;
54  nptr++;
55  } while(isdigit((unsigned char)*nptr));
56  }
57  }
58  if(valid && (*nptr == 'e' || *nptr == 'E')){
59  nptr++;
60  valid = false;
61  T psign = +1.0;
62  if(*nptr == '+'){
63  nptr++;
64  } else if(*nptr == '-'){
65  psign = -1.0;
66  nptr++;
67  }
68  if(isdigit((unsigned char)*nptr)){
69  valid = true;
70  T p = 0.0;
71  do {
72  p = p * 10.0 + (*nptr - '0');
73  nptr++;
74  } while(isdigit((unsigned char)*nptr));
75  value *= pow(10.0, (double)(psign * p));
76  }
77  }
78  if(valid){
79  *endptr = (char*)nptr;
80  } else {
81  *endptr = (char*)org;
82  }
83  return sign * value;
84 }
85 inline float strtof(const char* nptr, char** endptr) {
86  return strtofloat<float>(nptr, endptr);
87 }
88 inline double strtod(const char* nptr, char** endptr) {
89  return strtofloat<double>(nptr, endptr);
90 }
91 #endif
92 
93 }
94 
95 #endif
cnoid::strtod
double strtod(const char *nptr, char **endptr)
Definition: strtofloat.h:19
cnoid
Definition: AbstractSceneLoader.h:11
cnoid::strtof
float strtof(const char *nptr, char **endptr)
Definition: strtofloat.h:16