What's the correct result of below cast from char to string?
I heard that old boost version 1.46 lexical_cast output was 56, I don't have that version near me that I can't test it. But boost library(1.49) output is: 8
unsigned char c= 56;
std::string s = boost::lexical_cast<std::string>(c);
std::cout << "boost::lexical_cast: " << s << std::endl;
C++11 to_string output is: 56
std::cout << "std::to_string: " << std::to_string(c) << std::endl;
Both are correct. to_string
does not care that c
is of type char
, it will read the number in it and cast it into string.
On the other hand, lexical_cast<std::string>
seems to interpret variables of type char
as an ascii value. 56 is the ascii value of 8.
std::to_string
only provides overloads for numeric types, probably resolving to the unsigned
version in this case. lexical_cast
, OTOH, relies on std::ostream::operator<<
to perform the conversion, thus treating c
as a character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With