wcout 是如何工作的?

发布于 2024-12-03 08:38:07 字数 283 浏览 0 评论 0原文

我在控制台应用程序中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇纵 2024-12-10 08:38:07

wcout 可能会对输出进行一些 unicode 验证;如果验证失败,则输出失败。部分原因是 Windows 控制台子系统不能很好地处理 Unicode。

检查流是否设置了 failbitbadbit。重置流(例如wcout.clear())应该恢复流功能。

严格来说,cout 是一个std::basic_ostreamwcout 是一个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 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.

东北女汉子 2024-12-10 08:38:07

此示例调用未定义的行为。

operator<<(std::wostream&,const wchar_t*) 期望缓冲区以 null 终止,并在到达第一个 L'\0' 性格。如果缓冲区恰好包含空字符 (L'\0'),则代码将“正确”运行(尽管输出是不可预测的)。如果没有,则 operator<< 将继续读取内存,直到遇到一个。

您的示例不强制存在空终止符。相比之下,以下内容将打印未指定数量的字符,很可能是垃圾,但定义良好:

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

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文