0

The following code

#include <sstream>
#include <iostream>

int main() {
    uint8_t result = 0;
    std::stringstream ss("2B");
    ss << std::hex;
    ss >> result;

    std::cout << result;

    return 0;
}

outputs 2 with GCC 6.3 and 48 with clang on macOS. Why? The correct result is 43, and clearly it fits in uint8_t and even int8_t. However, replacing uint8_t with uint16_t results in 43.

Ideone link for this code

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • 2
    As for the reason why it happens, most likely because the `char` overload is picked which extracts one `char` from the stream, then `cout` prints this `char`. – Hatted Rooster Apr 13 '18 at 12:51
  • You need to analyse the code and the results more closely than that. Just getting the wrong result displayed doesn't (necessarily, and in this case) mean the read didn't work! – underscore_d Apr 13 '18 at 12:54
  • @SombreroChicken: that explains, thanks. – Violet Giraffe Apr 13 '18 at 13:02

0 Answers0