Read uint8_t from std::stringstream as a numeric type

前端 未结 3 698
自闭症患者
自闭症患者 2020-12-11 15:43

My understanding is that reading a uint8_t from a stringstream is a problem because the stringstream will interpret the uint8_t<

3条回答
  •  天涯浪人
    2020-12-11 16:02

    Please do not use char or unsigned char(uint8_t) if you want to read in a formatted way. Your example code and its result is an expected behavior.

    As we can see from https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2

    template< class Traits >
    basic_istream& operator>>( basic_istream& st, unsigned char& ch );
    

    This does "Performs character input operations".

    52 is an ascii code for '4'. Which means that the stringstream has read only one byte and still ready to read '6'.

    So if you want work in the desired way, you should use 2-byte or bigger integer types for sstream::operator>> then cast it to uint8_t - the exact way that you self-answered.

    Here's a reference for those overloads. https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt

提交回复
热议问题