Read uint8_t from std::stringstream as a numeric type

前端 未结 3 673
自闭症患者
自闭症患者 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:27

    After much back and forth, the answer seems to be that there is no standard way of doing this. The options are to either read off the uint8_t as either a uint16_t or std::string, and then convert those values to uint8_t:

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        uint8_t ui;
        uint16_t tmp;
        std::stringstream ss("46");
        ss >> tmp;
        ui = static_cast(tmp);
        cout << unsigned(ui);
        return 0;
    }
    

    However, such a solution disregards range checking. So you will need to implement that yourself if you need it.

提交回复
热议问题