4

Having been compiled using g++, the program below prints the std::wcout expression only. But if you uncomment the 8th row, it prints three expressions properly.

I would like to know the cause of such strange behavior.

#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;
}
cpp_enthusiast
  • 1,209
  • 8
  • 26

1 Answers1

4

Quoting from 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.

The reason it works when you use cout first is because your implementation allows wcout to output to byte-oriented streams. This is not guaranteed for all implementations. As mentioned in the quoted text, the only correct way to switch between them is with freopen like so:

#include <cstdio>
#include <iostream>

int main () {
  std::wcout << L"Hello" << std::flush;
  freopen(nullptr, "a", stdout);
  std::cout << " world\n" << std::flush;
}

But it's probably simpler to just avoid mixing them.

Kyle Willmon
  • 689
  • 2
  • 13