C ++-将浮点数组转换为std :: string [英] C++ - Convert array of floats to std::string

查看:246
本文介绍了C ++-将浮点数组转换为std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定长度的浮点数组。现在我想将该数组转换为二进制字符串。

I have an array of floats with a fixed length. Now I want to convert that array to a binary string.

我不能使用 const char * ,因为我的字符串会包含空字节。在这种情况下,我将如何使用memcpy?我已经尝试过 reinterpret_cast< string *> ,但这将不起作用,因为字符串也/仅存储了指向数据开头和结尾的指针(正确我是我错了)。

I cannot use const char * because my string will contain null-bytes. How would I use memcpy in that case? I have already tried a reinterpret_cast<string *>, but that won't work because the string is also/only storing pointers to the begin and end of the data (correct me if I am wrong).

我已经在构造一个空字符串:

I'm already constructing an empty string:

string s;
s.resize(arr_size);

但是我如何将浮点数数组复制到该字符串?

But how would I copy an array of floats to that string?

基本上,我想将固定浮点数组的内存区域转储到字符串中。

不要和我一起努力,我仍在学习c ++

Don't be to hard with me, I'm still learning c++

推荐答案

像这样:

#include <algorithm>
#include <string>

float data[10]; // populate

std::string s(sizeof data);
char const * p = reinterpret_cast<char const *>(data);

std::copy(p, p + sizeof data, &s[0]);

请注意,数据大小 10 * sizeof(float),即数组中的字节数。

Note that sizeof data is the same as 10 * sizeof(float), i.e. the number of bytes in the array.

更新:按照James的建议,您甚至可以做得更好,并一口气写出来:

Update: As suggested by James, you can do even better and write it all in one go:

char const * p = reinterpret_cast<char const *>(data);
std::string s(p, p + sizeof data);  // beginning + length constructor

甚至:

#include <iterator>

std::string s(reinterpret_cast<char const *>(std::begin(data)),  // begin + end
              reinterpret_cast<char const *>(std::end(data)));   // constructor

这篇关于C ++-将浮点数组转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆