Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a string into a double

Tags:

c

double

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?

like image 666
not_l33t Avatar asked May 18 '26 23:05

not_l33t


1 Answers

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
like image 80
terminus Avatar answered May 21 '26 16:05

terminus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!