I seem to be having some weird problem with atof() function not converting some values correctly. For the same values atoi() works perfectly.
Here's a little snippet of what I'm doing:
...
// frequencies is a std::string in format a10d50f20 etc. i.e. letter|frequency in %
// 6 - 48 characters, always correctly formatted
for (size_t i = 0; i < frequencies.size(); i+=3)
{
// #1
double percentage = atof(frequencies.substr(i+1, i+2).c_str()) / 100;
// #2
double percentage = static_cast<double>(atoi(frequencies.substr(i+1, i+2).c_str())) / 100;
cout << frequencies[i] << " - " << percentage << endl;
}
...
For some strange reason only method #2 seems to be always working correctly.
Both methods work correctly, giving me:
a - 0.30
b - 0.30
c - 0.40
with atof() I get:
a - 0.10
b - 0.10
c - 1000000000.00 !?
d - 1000000000.00 !?
e - 0.10
f - 0.50
while atoi() correctly gives me this:
a - 0.10
b - 0.10
c - 0.10
d - 0.10
e - 0.10
f - 0.50
p.s. I can't use std::stod because mingw...
The second argument of substr
is a length, not an offset.
When you call substr(i+1, i+2)
for d
you're getting the whole remainder of the string, which is then parsed as exponential notation 10e10
i.e. 10 * 1010.