I'm using strtok() to parse thru a line and read different numbers:
float value;
char *token;
token = strtok( line, " " );
...
sscanf( token, "%f", &value );
These results are less precise than I had expected:
token: -2324967.350950, value: -2324967.250000
token: -4669490.608992, value: -4669490.500000
token: 3658778.865353, value: 3658778.750000
I have to assume I'm missing something. Any ideas?
[Obligatory note]
The normal practice is to follow newsgroups and check the FAQ before
posting. With the use of groups.google, you can "follow" the newsgroup
in a much shorter time. Had you done this, you would have seen that
questions like yours have often been asked by others who failed to
follow the newsgroup or check the FAQ. You would have also seen many
pointers to the FAQ, where your problem is addressed.
[response to question]
Your problem has nothing to do with sscanf and everything to do with the
precision of variables. Your attempt to print more information than is
stored in a float is bound to be disappointing. Check the following
program (and try it out for your implementation):
#include <stdio.h>
#include <string.h>
#include <float.h>
int main(void)
{
char source[] = "-2324967.350950 -4669490.608992 3658778.865353";
char copy[sizeof source];
float fvalue;
double value;
long double lvalue;
char *token;
printf("[output]\n"
"I prefer to use the strto* family, "
"rather than sscanf, but ...\n");
printf("Results of conversion of tokens to float, "
"using sscanf.\n");
strcpy(copy, source);
for (token = strtok(copy, " "); token; token = strtok(0, " ")) {
sscanf(token, "%f", &fvalue);
printf("token: \"%s\", value: %.*g\n", token, FLT_DIG, fvalue);
}
printf("\nResults of conversion of tokens to double, "
"using sscanf.\n");
strcpy(copy, source);
for (token = strtok(copy, " "); token; token = strtok(0, " ")) {
sscanf(token, "%lf", &value);
printf("token: \"%s\", value: %.*g\n", token, DBL_DIG, value);
}
printf("\nResults of conversion of tokens to long double, "
"using sscanf.\n");
strcpy(copy, source);
for (token = strtok(copy, " "); token; token = strtok(0, " ")) {
sscanf(token, "%Lf", &lvalue);
printf("token: \"%s\", value: %.*Lg\n", token, LDBL_DIG,
lvalue);
}
return 0;
}
[output]
I prefer to use the strto* family, rather than sscanf, but ...
Results of conversion of tokens to float, using sscanf.
token: "-2324967.350950", value: -2.32497e+06
token: "-4669490.608992", value: -4.66949e+06
token: "3658778.865353", value: 3.65878e+06
Results of conversion of tokens to double, using sscanf.
token: "-2324967.350950", value: -2324967.35095
token: "-4669490.608992", value: -4669490.608992
token: "3658778.865353", value: 3658778.865353
Results of conversion of tokens to long double, using sscanf.
token: "-2324967.350950", value: -2324967.35095
token: "-4669490.608992", value: -4669490.608992
token: "3658778.865353", value: 3658778.865353