-
sscanf with double?
I'm trying to read a double from stdin in the following manner:
double value;
fgets(line, sizeof(line), stdin); // eg 12.54
sscanf(line, "%.2f", &value);
also tried %e, %g, %le, etc...none give the correponding double...can't seem to find the answer anywhere...please help!
-
Don't use a precision specifier for sscanf, and use %lf, %f is for floats. (note: this applies to scanf only, not printf).
Code:
#include <stdio.h>
int main(void)
{
char line[256];
double value;
fgets(line, sizeof(line), stdin);
sscanf(line, "%lf", &value);
printf("Value entered: %.2f\n", value);
return 0;
}
-
Is there any other way to make sure the number I get from stdin is a double, since sscanf cannot do it?
-
sscanf can do it.
Check the return value of sscanf is 1 (meaning it matched against the double specifier).
If you want to check there's no trailing cruft, then you can use the %n to write the current offset to a pointer to int, and make sure it has scanned the whole line (check your scanf documentation). Make sure you consider that sscanf won't take in the linefeed that fgets will leave.
Example:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[256];
double value;
int offset;
fgets(line, sizeof(line), stdin);
if (sscanf(line, "%lf%n", &value, &offset) != 1)
return 1;
if (offset != strlen(line)-1)
return 1;
printf("value: %.2f\n", value);
return 0;
}
My output:
Code:
Input: 12.34
Output: value: 12.34
Code:
Input: 12.34garbage
Result: returns 1
Code:
Input: garbage
Result: returns 1
Of course, if one wanted to read a double like this, one could just use strtod.
-
It does return 1 for numbers with double precision, but it also returns 1 for numbers with less/more precision...ie 12.22, 12.345, 12 all return 1 and I'm trying to make sure the only input allowed is 12.22.
I'm not sure what you mean by 'trailing cruft'...
-
Oh, that's not what "double precision" means. I thought you just wanted to know if they entered a valid string that can be converted into the double type.
If you want to check the precision, about the only solution that springs to mind is to count the number of characters in the string after the period ( . ).
By trailing cruft, I mean like 12.34foo, where the user has entered some garbage that doesn't pertain to the number, as in my example above.
-
And all this time i thought a double was a floating point number with 2 decimal places...anyways, thanks for the counting idea, that should work!