本文介绍了从std :: stringstream读取uint8_t作为数字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,从 stringstream 读取 uint8_t 是一个问题,因为 stringstream 会将 uint8_t 解释为 char 。我想知道如何从 stringstream 作为数字类型读取 uint8_t 。例如,以下代码:

My understanding is that reading a uint8_t from a stringstream is a problem because the stringstream will interpret the uint8_t as a char. I would like to know how I can read a uint8_t from a stringstream as a numeric type. For instance, the following code:

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    uint8_t ui;
    std::stringstream ss("46");
    ss >> ui;
    cout << unsigned(ui);
    return 0;
}

打印出 52 。我希望它打印出 46

prints out 52. I would like it to print out 46.

编辑:另一种方法是只从 stringstream string c $ c>,然后将解决方案转换为 uint8_t ,但这会破坏不错的链接属性。例如,在我必须编写的实际代码中,我经常需要这样的东西:

An alternative would to just read a string from the stringstream and then convert the solution to uint8_t, but this breaks the nice chaining properties. For example, in the actual code I have to write, I often need something like this:

   void foobar(std::istream & istream){
       uint8_t a,b,c;
       istream >> a >> b >> c;
       // TODO...
   }


推荐答案

您可以为 uint8_t 重载输入 operator>> ,例如:

You can overload the input operator>> for uint8_t, such as:

std::stringstream& operator>>(std::stringstream& str, uint8_t& num) {
   uint16_t temp;
   str >> temp;
   /* constexpr */ auto max = std::numeric_limits<uint8_t>::max();
   num = std::min(temp, (uint16_t)max);
   if (temp > max) str.setstate(std::ios::failbit);
   return str;
}

实时演示:

说实话我不确定这样的解决方案是没有问题的。

To say the truth I am not sure whether such a solution is problem-free. Someone more experienced might clarify.

更新

请注意,此解决方案通常不适用于 std :: basic_istream (以及实例 std :: istream ),因为 unsigned char operator>> 过载:。然后,行为将取决于如何实现 uint8_t

Note that this solution is not generally applicable to std::basic_istream (as well as it's instance std::istream), since there is an overloaded operator>> for unsigned char: [istream.extractors]. The behavior will then depend on how uint8_t is implemented.

这篇关于从std :: stringstream读取uint8_t作为数字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:07