What is the correct result of boost :: lexical_cast and std :: to_string for unsigned char

What is the correct result below made from char to string?

I heard that the older version 1.46 lexical_cast was 56 , I don’t have this version next to me, that I can’t test it. But boost library (1.49): 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: 56

  std::cout << "std::to_string: " << std::to_string(c) << std::endl; 
+4
source share
5 answers

Invalid version of old acceleration.

The result of lexical_cast should be the same as the streaming in ostream. Thus, the result

 std::cout << boost::lexical_cast<std::string>(x) 

coincides with

 std::cout << x 

In the case of unsigned char this means interpreting x as an ASCII code, for other integer types it will give the same result as itoa . This is because char types are not considered upstream arithmetic integers (see Β§ 27.3.6.2 and Β§ 27.3.6.4). The advantage of this approach is that you can output a string by printing its individual characters. If you want an actual numeric value, you can always make char an arithmetic type for output.

to_string , on the other hand, works like itoa for all integer data types, since it has no overload for unsigned char . The rationale here is that by calling to_string , you have already expressed your intention to perform the conversion, that is, you are not interested in the quality of the character quality values ​​(which would be the default), but arithmetic type quality.

+3
source

std::to_string only provides overloads for numeric types, perhaps in this case it allows the unsigned version. lexical_cast , OTOH, relies on std::ostream::operator<< to perform the conversion, thus treating c as a character.

+8
source

Both are correct. to_string doesn’t care that c is of type char , it will read the number in it and put it in a string.

On the other hand, lexical_cast<std::string> seems to interpret char variables as an ascii value. 56 is the value of ascii 8.

+5
source

This is a matter of interpretation. If you interpret char as a small integer, you print its code in the current character set; this is what to_string does.

If you interpret it as a printed character, you issue the corresponding character, i.e. 8 as boost::lexical_cast .

+2
source

This is not a char for the string, it is an "unsigned char" for the string. And they are both correct. lexical_cast converts using an instance of stringstream, while std :: to_string is overloaded for unsigned, which means that unsigned char advances to unsigned int.

+1
source

Source: https://habr.com/ru/post/1484608/


All Articles