How to insert NULL character in std::wstringstream?

135 Views Asked by At

I need to construct a multi-string (REG_MULTI_SZ) in C++ from a list of values represented in a std::vector<std::wstring>.

This is what first came to mind but was of course incorrect:

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();
}

Upon inspection, the returned string didn't have any embedded NULL characters.

2

There are 2 best solutions below

9
Igor Levicki On BEST ANSWER

The solution is actually quite simple:

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();
}

The reason why the original code failed to accomplish anything is that ss << L"\0"; is the same as ss << L""; and therefore does nothing.

You can also pass 0 instead of L'\0':

        ss.put(0);

Or use << and std::ends:

        ss << std::ends;

Or use << and C++ string literal operator""s:

        using namespace std::string_literals;
        // ...
        ss << L"\0"s;

Or even basic_ostream::write:

        const wchar_t Null = 0;
        // ...
        ss.write(&Null, 1); // sizeof(Null) / sizeof(wchar_t)
0
T.C. On

There's an obscure manipulator in the standard library for this too:

ss << std::ends;