如何将boost :: asio :: streambuf转换为float?

时间:2016-01-29 02:54:35

标签: c++ boost serial-port

我正在从串口读取数据。我已经设法获得端口设置,并且可以读入缓冲区,但我无法弄清楚如何将缓冲区保存的数据转换为浮点数。

float Serial::ReadData()
{
    boost::asio::streambuf buff;
    int bytesRead = read_until(*port, buff, "\n");
    boost::asio::const_buffers_1 constBuff = buff.data();
    char*data = nullptr;
    int pos = 0;
    for (auto buffer = constBuff.begin(); buffer != constBuff.end(); buffer++)
    {
        data[pos] = reinterpret_cast<char>(buffer);
        pos++;
    }
    buff.consume(bytesRead);
    return atof(data);
}

2 个答案:

答案 0 :(得分:0)

替代地

<强> Live On Coliru

现在它看起来几乎相同,但是:

  • 它不会泄漏内存
  • 它不会不必要地复制缓冲区
  • 它处理错误
  • 如果你想解析超过1件事情,那就更灵活了
#include <boost/asio.hpp>
#include <iostream>
#include <stdexcept>

struct Serial {
    float ReadData();

    boost::asio::serial_port* port = nullptr;
};

float Serial::ReadData()
{
    boost::asio::streambuf buff;
    /*int bytesRead = */read_until(*port, buff, "\n");
    std::istream is(&buff);
    float f;
    if (is >> f)
        return f;
    throw std::invalid_argument("ReadData");
}

int main(){}

答案 1 :(得分:-1)

好吧,我想出了怎么做。这比我原先想象的要简单得多。

float Serial::ReadData()
{
    boost::asio::streambuf buff;
    int bytesRead = read_until(*port, buff, "\n");
    char*data = new char[bytesRead];
    buff.sgetn(data, bytesRead);
    return atof(data);
}