C/C++ sscanf exponential value error

Started by
4 comments, last by faculaganymede 15 years, 6 months ago
Hi all, I am trying to use sscanf to extract an exponential value from a string, which should work according to the documentation. But, in my code, it doesn't seem to be working, the exponential value retrieved is not the correct value. Do you see any errors?

#include<iostream>
#include<string>

using namespace std;

int main()
{

    char str[]="240.0000  2.015E+02  2.020E+01";
    float junk;
    double val1, val2;

    sscanf(str, "%f %e %e", &junk, &val1, &val2);

    cout<<junk<<endl;
    cout<<val1<<endl;
    cout<<val2<<endl;
}



Advertisement
'Junk' should be a double variable, not a float. The only floating point types scanf can read is double and long double. The same is true for printf actually, but any float in an ellipsis is implicitly upcast to a double.
Thanks for your quick reply, implicit.

But, if I change junk to double, all 3 values are wrong:

-9.25596e+061
-9.25596e+061
-9.25596e+061
Press any key to continue . . .

Before, at least junk (as a float) returns the correct value.
It seems I was wrong, sorry. Apparently float is the default and you need a 'l' prefix to get doubles (e.g. "%lf") or 'L' for a long double.

I could've sworn they were doubles... Oh well, that ought to teach me to verify my claims before posting, or at least to try using scanf once in a while.
You were wrong in specifics, but right in generalities. All three variables must have float type if those format specifiers are used. (There is no difference between the %e and %f specifiers.)
Thanks so much, "%lf" worked! I haven't programed in C/C++ for awhile and totally forgot about it. I am surprised there's no mentions of the "l" in the documents, for example:

http://www.uwm.edu/cgi-bin/IMT/wwwman?topic=sscanf&msection=

This topic is closed to new replies.

Advertisement