wcout 是如何工作的?
我在控制台应用程序中使用 wcout 时注意到一个奇怪的问题。
调用某个函数后,其余的 wcout 调用根本不起作用。即输出语句没有出现在控制台上。
我注意到在函数中,我使用了一个从未分配的宽字符数组。
WCHAR wArray[1024];
wcout<<wArray<<endl;
就在这个电话之后,所有其他的工作都停止了。
所以,我只是想知道 wcout 与 cout 有何不同,以及为什么会出现这个问题,
I noticed a weird problem while using wcout in a console application.
After 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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
wcout
可能会对输出进行一些 unicode 验证;如果验证失败,则输出失败。部分原因是 Windows 控制台子系统不能很好地处理 Unicode。检查流是否设置了
failbit
或badbit
。重置流(例如wcout.clear()
)应该恢复流功能。严格来说,
cout
是一个std::basic_ostream
,wcout
是一个std::basic_ostream
code> ...这就是差异所在。只是如果要使 Unicode 格式良好,则对 Unicode 有更多要求。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
orbadbit
set. Resetting the stream (e.g.wcout.clear()
) should restore stream functionality.Strictly speaking,
cout
is astd::basic_ostream<char>
andwcout
is astd::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.此示例调用未定义的行为。
operator<<(std::wostream&,const wchar_t*)
期望缓冲区以 null 终止,并在到达第一个L'\0'
性格。如果缓冲区恰好包含空字符 (L'\0'
),则代码将“正确”运行(尽管输出是不可预测的)。如果没有,则operator<<
将继续读取内存,直到遇到一个。您的示例不强制存在空终止符。相比之下,以下内容将打印未指定数量的字符,很可能是垃圾,但定义良好:
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 firstL'\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, thenoperator<<
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: