Igo*_*cki 6 c++ std stringstream
我需要REG_MULTI_SZ在 C++ 中从 .a 表示的值列表构造一个多字符串 () std::vector<std::wstring>。
这是首先想到的,但当然是错误的:
std::wstring GetMultiString(std::vector<std::wstring> Values)
{
std::wstringstream ss;
for (const std::wstring& Value : Values) {
ss << Value;
ss << L"\0";
}
ss << L"\0";
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
经检查,返回的字符串没有任何嵌入的 NULL 字符。
解决方案其实很简单:
std::wstring GetMultiString(std::vector<std::wstring> Values)
{
std::wstringstream ss;
for (const std::wstring& Value : Values) {
ss << Value;
ss.put(L'\0');
}
ss.put(L'\0');
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
原始代码未能完成任何事情的原因是与ss << L"\0";相同ss << L"";,因此什么也没做。
您还可以通过0而不是L'\0':
ss.put(0);
Run Code Online (Sandbox Code Playgroud)
或者使用<<std ::ends:
ss << std::ends;
Run Code Online (Sandbox Code Playgroud)
或者使用<<C++ 字符串文字运算符""s:
using namespace std::string_literals;
// ...
ss << L"\0"s;
Run Code Online (Sandbox Code Playgroud)
const wchar_t Null = 0;
// ...
ss.write(&Null, 1); // sizeof(Null) / sizeof(wchar_t)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |