#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;
}
C/C++ sscanf exponential value error
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?
'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.
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.
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.)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement