问题描述
我正在尝试将BYTES的std :: vector(或无符号字符)转换为std :: string。
我的问题是向量的第一个元素为0时,转换后返回的是空字符串。
I am trying to convert a std::vector of BYTES (or unsigned char) to a std::string.The problem I have is when the first element of the vector is a 0, then this returns an empty string after the conversion.
我尝试了2下面的方法。 string1和string2都返回一个空字符串。
我期望的结果是一个以2 x 0s开头的字符串,后跟其他几个字符。
I have tried the 2 methods below. Both string1 and string2 return an empty string.The result I am expecting is a string that starts with 2 x 0s followed by several other characters.
// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data;
// method 1
BYTE* pByteArray = &data[0];
std::string string1 = reinterpret_cast<LPCSTR>(pByteArray);
// method 2
std::string string2(data.begin(),data.end());
// both string1 and string2 return ""
我猜是因为向量中的第一个BYTE为0,因此字符串分配认为它为null或为空。
为了返回字符串的其余部分,我还可以做一些其他转换吗?
I am guessing because the first BYTE in the vector is a 0, so the string assignment is thinking it's null or empty.Is there some other conversion I can do in order to return the rest of the string?
任何帮助我们都非常感谢。
Any help greatly appreciated.
推荐答案
第二个并不是真的空,请考虑:
The second is not really empty please consider:
// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data = {0, 35, 35 ,38};
// method 2
std::string string2(data.begin(),data.end());
cout<< (string2.data()+1) << " size:"<< string2.size() << endl;
/* Notice that size is 4 */
在
编辑检查大小甚至更简单它是 4 。
Edit Checking the size is even more trivial as it's 4.
关于数据
和 null
作为友好地解释(强调我的意思):
Regarding data
and null
termination as the docs kindly explain (emphasis mine):
一种 c ++ 98安全方式可能看起来:
A "c++98 safe" way could look like:
cout.write(string2.data()+1, string2.size()-1);
无论如何,打印只是为了演示字符串 non-emptiness:)
Anyway the printing is just to demonstrate the strings "non-emptiness" :)
这篇关于C ++转换向量< BYTE>到第一个向量字节为0的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!