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.