使用 g++ 编译后,下面的程序仅打印 std::wcout
表达式。但如果您取消第 8 行的注释,它会正确打印三个表达式。
我想知道这种奇怪行为的原因。
#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;
}
引自this page
A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout.
当您首先使用 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;
}
但避免混合它们可能更简单。