converting a string into a double

后端 未结 4 1350
感动是毒
感动是毒 2020-12-12 00:28

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

相关标签:
4条回答
  • 2020-12-12 00:48
    1. Why are you not using fgets()?
    2. You're looking for atof().

    (Thanks to R. for fixing my idiotic suggestion in part 1)

    0 讨论(0)
  • 2020-12-12 00:53

    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
    
    0 讨论(0)
  • 2020-12-12 01:01

    Use strtod, that's what it's for. And fgets can replace your safeGetString function.

    0 讨论(0)
  • 2020-12-12 01:02

    Any of:

    • strtod()
    • atof()
    • sscanf()

    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 ) ;
    
    0 讨论(0)
提交回复
热议问题