I am looking for a way to get floating point input from a user.
My way of going about this is to use a self-made getstrn function and plug that into another function
fgets()
?atof()
.(Thanks to R. for fixing my idiotic suggestion in part 1)
Try the strtod function:
char *end;
double num = strtod(arr, &end);
The end will point after the last char that was processed. You can set the second to NULL
if you don't care about that. Or you can use atof
: atof(str)
is equivalent to strtod(str, (char **)NULL)
.
But you should care, since you can check if the input is malformed:
if (*end != '\0')
// Handle malformed input
Use strtod
, that's what it's for. And fgets
can replace your safeGetString
function.
Any of:
Of these sscanf offers the strongest validation, since the other two return a valid double value of 0.0 if the input cannot be interpreted as a double, while sscanf() returns the number of format specifiers successfully matched to the input. So:
input_valid = (sscanf( arr, "%lf", value ) != 0 ) ;