Sign in to follow this  
faculaganymede

C/C++ sscanf exponential value error

Recommended Posts

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;
}



Share this post


Link to post
Share on other sites
'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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
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=

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this