我正在尝试将 BYTES(或无符号字符)的 std::vector 转换为 std::string。 我遇到的问题是当 vector 的第一个元素是 0 时,转换后返回一个空字符串。
下面两种方法我都试过了。 string1 和 string2 都返回一个空字符串。 我期望的结果是一个以 2 x 0 开头后跟几个其他字符的字符串。
// 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 ""
我猜是因为 vector 中的第一个 BYTE 是 0,所以字符串赋值认为它为 null 或空。 为了返回字符串的其余部分,我可以做一些其他转换吗?
非常感谢任何帮助。
最佳答案
第二个不是真的空请考虑:
// 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 */
关于 ideone
编辑 检查大小更加简单,因为它是 4。
将data
和null
终止视为docs请解释(强调我的):
The returned array is null-terminated, that is, data() and c_str() perform the same function. If empty() returns true, the pointer points to a single null character. (since C++11)
一种“c++98 安全”的方式可能看起来像like :
cout.write(string2.data()+1, string2.size()-1);
无论如何打印只是为了证明字符串“非空”:)
关于C++ 将 Vector<BYTE> 转换为第一个 vector 字节为 0 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015126/