In the header of C++11, there are three new functions for conversion between number and string.
std::string std::to_string(unsigned long long);
std::string std::to_string(long double);
std::string std::to_string(long long);
The first question – why there is only 3 functions? What about simple int or unsigned int, etc.?
The second question – why to_string doesn’t throw exception in following code?
long double x = std::numeric_limits<long double>::quiet_NaN();
std::string i = std::to_string( x );
long double c = std::stold( i ); // i = "1.#QNAN"
And the third question – why c equals 1.0 ?
“As long as it yields the behavior described, do what you please..“
All intrinsic numeric types can implicitly be converted to either
unsigned long long,long doubleorlong longand still hold the precision required, therefore no more overloads are necessary.The standard says that the following functions should be defined, though a lib confirming to the standard is free to do “whatever it wants” as long as it yields the same behavior as described.
Why should it throw an exception?
std::numeric_limits<long double>::quiet_NaN();is a valid value, andstd::to_string (T)is described in the standard to yield the same behavior as callingsprintfwith the appropriate format-string.On what compiler iscequal to1.0?The conversion should yield a
NaN-value if the value ofiis string representation ofNaN(not containing any digits).If no suitable conversion can be found the function is described to throw
invalid_argument.MSVC will yield
1.#QNANwhen trying to convertstd::numeric_limits<long double>::quiet_NaN();to astd::string.When using
std::stoldit will look for the first none whitespace character, and then use as many digits as found (in this case only1), thereforecwill be equal to1.0after the function call.