Pregunta

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.

Sample Outputs

FOR: frequencies = "a30b30c40"

Both methods work correctly, giving me:
a - 0.30
b - 0.30
c - 0.40

FOR: frequencies = "a10b10c10d10e10f50"

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...

¿Fue útil?

Solución

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.

Otros consejos

For d the atof function took 10e10 as 10 x (10 ^ 10) = 1000000000.0 (in engineering notation / standard form).

Did you really get 1000000000.0 for c? I dunno if the same thing happened as well.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top