Raf*_*afa 0 c++ string byte vector zero
我试图将BYTES(或unsigned char)的std :: vector转换为std :: string.我遇到的问题是当向量的第一个元素是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 ""
Run Code Online (Sandbox Code Playgroud)
我在猜测因为向量中的第一个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 */
Run Code Online (Sandbox Code Playgroud)
关于意识形态
编辑检查大小更加微不足道,因为它是4.
关于data和null终止,因为文档善解释(强调我的):
返回的数组以空值终止,即data()和c_str()执行相同的功能.如果empty()返回true,则指针指向单个空字符.(自C++ 11以来)
"c ++ 98安全"方式可能如下所示:
cout.write(string2.data()+1, string2.size()-1);
Run Code Online (Sandbox Code Playgroud)
无论如何打印只是为了演示字符串"非空虚":)
| 归档时间: |
|
| 查看次数: |
12822 次 |
| 最近记录: |