- Thu Jan 05, 2017 8:35 pm
#60511
I've taken the code for strtod (alias for atof) and modified it to create function atof_e.
I had initially modified strtod so both atof and strtod would work properly - but this would require more work for someone else if they wish to use this code: you'd have to find and modify the appropriate library. Also, if I or someone else later updates to a newer version of the library the modification might well be overwritten with the old bugged version, and I/you will probably have forgotten about this modification.
Usage for the modified function:
double atof_e (const char* str);
Identically to atof(), atof_e() parses the string str, interpreting its content as a floating point number and returns its value as a double. As per the C++ 98 specification, it may optionally followed by an exponent part (an e or E character followed by an optional sign and a sequence of digits).
Code: Select alldouble atof_e(const char* str) {
char ** endptr;
double result = 0.0;
double factor = 1.0;
bool exp_factor = 1; //default 1 - positive exponent. Use 0 for negative
double exponent = 0;
double multiplier = 1; //multiplier for exponent
bool decimals = false;
char c;
while(isspace(*str)) {
str++;
}
if(*str == 0x00) {
// only space in str?
if (endptr) *endptr = (char*) str;
return result;
}
if(*str == '-') {
factor = -1;
str++;
} else if(*str == '+') {
str++;
}
while((c = *str)) {
if(c == '.') {
decimals = true;
str++;
continue;
}
if (c == 'e' || c == 'E') {
str++;
if(*str == '-') {
exp_factor = 0;
str++;
} else if(*str == '+') {
str++;
}
while (c = *str) { //this while loop for the exponent
int d = c - '0';
if (d < 0 || d > 9) {
break;
}
exponent = exponent * 10 + d;
str++;
}
}
else {
int d = c - '0';
if(d < 0 || d > 9) {
break;
}
result = 10.0 * result + d;
if(decimals) {
factor *= 0.1;
}
str++;
}
}
if (endptr) *endptr = (char*) str;
result *= factor;
if (exponent) {
multiplier = pow(10, exponent);
if (exp_factor) result *= multiplier;
else result /= multiplier;
}
return result;
}