我正在从串口读取数据。我已经设法获得端口设置,并且可以读入缓冲区,但我无法弄清楚如何将缓冲区保存的数据转换为浮点数。
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);
}
答案 0 :(得分:0)
替代地
<强> Live On Coliru 强>
现在它看起来几乎相同,但是:
#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);
}