Saddle Point
Saddle Point

Reputation: 3225

What is the equivalent of char(0) or '\0' for wchar_t?

#include <iostream>
#include <locale>

int main(int argc, char** argv) {
    std::wcout.imbue(std::locale("zh_CN.UTF-8"));

    std::wcout << wchar_t(0) << L"哈哈" << std::endl;
    std::cout << char(0) << "haha" << std::endl;
    std::cout << "---------------" << std::endl;

    std::wcout.clear();
    std::wcout << L"哈哈" << std::endl;
    std::cout << "haha" << std::endl;
    std::cout << "---------------" << std::endl;

    std::wcout << L'\0' << L"哈哈" << std::endl;
    std::cout << '\0' << "haha" << std::endl;
    std::cout << "---------------" << std::endl;

    std::wcout.clear();
    std::wcout << L"哈哈" << std::endl;
    std::cout << "haha" << std::endl;

    return 0;
}

The wchar_t(0) and L'\0' seem to different from char(0) and '\0' and cause the ostream to have bad state.

It took me some time to figure out the missing output is not caused by the locale setting but the wchar_t since my original program has somewhere output a wchar_t(0) or '\0'.

My question is how are they different from the char version? And how to correctly use an empty wchar_t?

Thanks in advance.

Upvotes: 2

Views: 1289

Answers (1)

M.M
M.M

Reputation: 141638

The null wide character can be written as wchar_t(0) or L'\0'.

The different behaviour you observe is because cout and wcout are text streams. According to cppreference, you should only use printable characters, \t and \n on a text stream. Sending a null character to the text stream may have unexpected results.

If you want to use cout as a binary stream in Windows there are some hacks you can do , see here for ideas.

I am not sure whether those hacks would work for wcout; but from past experience, the status of wcout support in compilers is dubious and I have found it more reliable to just use stdout and do any required translation using facets or explicit functions etc.

Upvotes: 3

Related Questions