c++stdstringstream

How to insert NULL character in std::wstringstream?


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.


Solution

  • 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)