return value of strtod() if string equals to zero

前端 未结 2 821
温柔的废话
温柔的废话 2021-01-21 17:00

As per MSDN:

  • strtod returns 0 if no conversion can be performed or an underflow occurs.

What if my string equals to zero (i.e., 0.0000)

相关标签:
2条回答
  • 2021-01-21 17:46

    Use the str_end parameter of the function. For example:

    const char* str = "123junk";
    char* str_end;
    double d = strtod(str, &str_end);
    // Here:
    //   d will be 123
    //   str_end will point to (str + 3) (the 'j')
    
    // You can tell the string has some junk data if *str_end != '\0'
    if (*str_end != '\0') {
        printf("Found bad data '%s' at end of string\n", str_end);
    }
    

    If conversion totally fails, str will equal str_end:

    const char* str = "junk";
    char* str_end;
    double d = strtod(str, &str_end);
    // Here:
    //   d will be 0 (conversion failed)
    //   str_end will equal str
    
    if (str == str_end) {
        printf("The string doesn't start with a number!\n");
    }
    

    You can combine these two methods to make sure the string was (completely) successfully converted (that is, by checking str != str_end && *str_end == '\0')

    0 讨论(0)
  • 2021-01-21 17:52

    The signature is (give or take restrict keywords):

     double strtod(const char *nptr, char **endptr);
    

    If you pass a non-null pointer as the second argument, it will be returned with the value of nptr if it could perform no conversion. If it found a genuine zero in the input string, then the value stored in *endptr won't be nptr.

    char *end;
    const char *data = "0.00000";
    
    errno = 0;
    double d = strtod(data, &end);
    if (end != data)
        ...a conversion was performed...
    else
        ...trouble...
    

    You can also look at errno, but you need to zero it before the call because no function in the standard C library or the POSIX library sets errno to zero.

    The standard says:

    If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

    Returns

    The functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value overflows and default rounding is in effect (7.12.1), plus or minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the return type and sign of the value), and the value of the macro ERANGE is stored in errno. If the result underflows (7.12.1), the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type; whether errno acquires the value ERANGE is implementation-defined.

    0 讨论(0)
提交回复
热议问题