使用stringstream,我如何解析这些字符串?

时间:2013-03-21 09:24:41

标签: c++ parsing tcp

我有一个tcp客户端,它从服务器获取数据作为字符串流。服务器将向量(浮点数)打包在一个大字符串中,并用标志分隔它们。现在在我的客户端,我再次分离这些标志,并将它们存储在一个字符串数组中。所以每个“Token”应该是一个向量。 但我只是无法解析它。字符串我看起来很奇怪,看看:enter image description here

所以,我需要做的就是将其解析为3个浮点数。在服务器端,它的发送方式如下:

data.addFlag(11);
data << pelvis.x() << pelvis.y() << pelvis.z();
data.addFlag(12);
data << rhip.x() << rhip.y() << rhip.z();

运算符过载的地方

operator<<(const float& f)
{
m_buf.append(reinterpret_cast<const char*>(&f), sizeof(f));
return *this;
}

修改

一个令牌如下所示:如果我尝试通过

解析它
float first = *reinterpret_cast<float*>(value)

我得到一个例外。 enter image description here

1 个答案:

答案 0 :(得分:2)

这些字符串看起来很好,你只需要明白,当你将浮点数重新解释为字符数组时,你将无法获得人类可读的东西。您可以在此处查看浮点数如何表示为二进制:Floating points tutorial

因此,如果您有浮点数1.01,您将获得二进制00111111100000010100011110101110,这是十六进制0x3f8147ae,如果您查看ascii表中的每个字节,您将看到这些字节可能看起来像垃圾。

所以对你的问题:如果你看{4},你会发现每个浮点数是4个字节。

假设你有一个12字节的字符串(你应该这样做),你应该意识到那里有3个浮点数。要将它们取出,一次获取4个字节并重新解释它们

(未经测试的代码)

string data = (however you got the data)
float first = *reinterpret_cast<float*>(&data[0]);
float second = *reinterpret_cast<float*>(&data[4]);
float third = *reinterpret_cast<float*>(&data[8]);

就是这样。

编辑:似乎我忘记了取消引用指针。

请参阅此处查看工作示例:

here

相关问题