c++ - 混合 std::wcout 和 std::cout 会出错,有什么问题吗?

标签 c++ cout widechar

<分区>

使用 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;
}

但避免混合它们可能更简单。

关于c++ - 混合 std::wcout 和 std::cout 会出错,有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958929/

相关文章:

C++ char 数组的动态数组

c++ - Ofstream 返回垃圾。 Cout 工作......为什么不流?

c++ - 一个字符串的 Cout 给出了一个错误并且很难有一些洞察力帮助吗?

c++ - 在 C++ 中给出意外输出的简单代码

c - 哪些宽字符被翻译成空多字节?

c++ - 虚幻引擎 4:Super::Tick ( DeltaTime )

c++ - 从证书中获取 "Key Usage"

c++ - 在创建过程中调用对象方法 C++

c - wprintf : %p with NULL pointer

c++ - printf ("%s")、printf ("%ls")、wprintf ("%s") 和 wprintf ("%ls") 之间有什么区别?