return value of strtod() if string equals to zero

前端 未结 2 820
温柔的废话
温柔的废话 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')

提交回复
热议问题