Jump to content
  • Advertisement
Sign in to follow this  
faculaganymede

C/C++ sscanf exponential value error

This topic is 3633 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

Share this post


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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!