开发者

How does wcout work?

开发者 https://www.devze.com 2023-04-02 16:11 出处:网络
I noticed a weird problem while using wcout in a console application. Aft开发者_如何学运维er calling a certain function, the rest of the wcout calls did not work at all. i.e. the output statements di

I noticed a weird problem while using wcout in a console application.

Aft开发者_如何学运维er calling a certain function, the rest of the wcout calls did not work at all. i.e. the output statements did not appear on the console.

I noticed that in the function, I had used a wide character array which was never assigned.

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

It was after this call, all the other wcout's stopped working.

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


wcout may be doing some unicode validation on the output; and failing the output if validation fails. This is in part because the Windows console subsystem does not handle Unicode very well.

Check whether or not the stream has failbit or badbit set. Resetting the stream (e.g. wcout.clear()) should restore stream functionality.

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


This example invokes undefined behavior.

operator<<(std::wostream&,const wchar_t*) expects the buffer to be null terminated, and stop printing characters when it reaches the first L'\0' character. If the buffer happens to contain a null character (L'\0'), then the code will run "correctly" (although the output is unpredictable). If it doesn't, then operator<< will keep reading the memory until it encounters one.

The presence of a null terminator is not enforced by your example. In comparison, the following would print an unspecified number of characters, most likely junk, but is well defined:

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

精彩评论

暂无评论...
验证码 换一张
取 消