How does wcout work?

I noticed a strange problem when using wcout in a console application.

After calling a specific function, the rest of the wcout calls do not work at all. that is, the output commands did not appear on the console.

I noticed that in this function I used a wide array of characters that was never assigned.

WCHAR wArray[1024]; wcout<<wArray<<endl; 

After this call, everything else stopped working.

So, I was just interested to know what makes wcout different from cout, and why this problem arose,

+4
source share
2 answers

This example invokes undefined behavior.

operator<<(std::wostream&,const wchar_t*) expects the buffer to be completed with a zero value and stop printing characters when it reaches the first character L'\0' . If the buffer contains a null character ( L'\0' ), then the code will work "correctly" (although the output is unpredictable). If this is not the case, operator<< will continue to read the memory until it encounters it.

Having a null terminator does not apply in your example. For comparison, the following will print an unspecified number of characters, most likely garbage, but clearly defined:

 WCHAR wArray[1024]; wArray[1023] = L'\0'; wcout << wArray << endl; 
+4
source

wcout may do some unicode checking on the output; and exit failure if verification fails. This is partly because the Windows console subsystem does not handle Unicode very well.

Check if the failbit or badbit stream is badbit . Resetting the stream (e.g. wcout.clear() ) should restore the functionality of the stream.

Strictly speaking, cout is std::basic_ostream<char> , and wcout is std::basic_ostream<wchar_t> ... and what the differences really std::basic_ostream<wchar_t> . It's just that there are more requirements for Unicode if this Unicode needs to be well formed.

+5
source

All Articles