假设 float 或 double NaN 总是 "nan" 作为字符串是否安全?

Is it safe to assume that float or double NaNs will always be "nan" as a string?

如果我通过 std::cout 打印 NaN 或将其转换为字符串,标准是否规定它必须是 "nan" 作为字符串?

是否有其他方法可以将 NaN 转换为字符串,但事实并非如此?

#include <iostream>
#include <limits>

int main() {    

    float x = std::numeric_limits<float>::quiet_NaN();
    std::cout << x << '\n';                 // Output: nan
    std::cout << std::to_string(x) << '\n'; // Output: nan
    printf("%f", x);                        // Output: nan

    // possibly other variants to print x
}

std::to_string is defined in terms of std::sprintf,C++从C99标准库中采用。上面写着:

Not-a-number is converted to nan or nan(char_sequence). Which one is used is implementation defined.

因此字符串将以 nan 开头,但后面可能还有其他字符。

不幸的是,Microsoft 的库似乎不兼容。看到这个答案:

So, after taking all that in, the end result is that your C standard library is not C99-compliant, since 1.#QNAN is not a valid output of fprintf according to the above. But, it's well-known that Microsoft's C runtime is not C99-compliant, and it doesn't plan to become compliant any time soon, as far as I'm aware.


(Off-topic)
不要使用 std::endl,除非你真的想要 '\n' << std::flush.

的缩写形式

添加到@Nikos C.:

std::cout 这是关于格式的 std::basic_ostream leads to std::num_put

If the type of v is a floating-point type, the the first applicable choice of the following is selected:

If floatfield == std::ios_base::fixed, will use conversion specifier %f 
If floatfield == std::ios_base::scientific && !uppercase, will use conversion specifier %e 
If floatfield == std::ios_base::scientific, will use conversion specifier %E

所以我要得出结论,std::cout 也与 printf

相关联