使用g ++进行编译后,下面的程序std::wcout仅显示表达式。但是,如果您取消注释第八行,它将正确打印三个表达式。
我想知道这种奇怪行为的原因。
#include <iostream>
#include <cstring>
#include <boost/format.hpp>
int main () {
int x = 10;
wchar_t str[] = L"Hello, world!";
// std::cout << "what?" << std::endl;
std::wcout << L"str = \"" << str << L"\" | len = " << wcslen(str) << L"\n";
std::cout << boost::format("x = %d | &x = %p") % x % &x << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
引用此页
程序不应将cout上的输出操作与wcout上的输出操作(或stdout上的其他宽方向的输出操作)混合:一旦对其中一个执行了输出操作,则标准输出流将获得方向(窄或宽)只能通过在stdout上调用freopen来安全地更改它。
cout初次使用时起作用的原因是,您的实现允许wcout输出到面向字节的流。并非所有实现都可以保证。如引用的文本中所述,在它们之间进行切换的唯一正确方法是freopen像这样:
#include <cstdio>
#include <iostream>
int main () {
std::wcout << L"Hello" << std::flush;
freopen(nullptr, "a", stdout);
std::cout << " world\n" << std::flush;
}
Run Code Online (Sandbox Code Playgroud)
但是避免混合它们可能更简单。
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |