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 which would convert the string into a double.
My safe get string:
void safeGetString(char arr[], int limit){
int c, i;
i = 0;
c = getchar();
while (c != '\n'){
if (i < limit -1){
arr[i] = c;
i++;
}
c = getchar();
}
arr[i] = '\0';
}
What would be the best way to write this get_double function?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With