24

In c++ what is the difference between std::cout and std::wcout?

They both control output to a stream buffer or print stuff to the console, or are they just alike ?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Whizz Mirray
  • 380
  • 1
  • 3
  • 9
  • 6
    The w versions of standard streams are for **w**ide characters. – NathanOliver Sep 01 '15 at 18:25
  • They don't "print to the console". They write to stdout. Often, stdout is associated with a tty. Sometimes (rarely), the terminal you are using is a console. Don't conflate stdout with the terminal, and don't refer to your terminal as a "console". – William Pursell Feb 21 '22 at 14:27

2 Answers2

31

They operate on different character types:

  • std::cout uses char as character type
  • std::wcout uses wchar_t as character type

Otherwise both streams write to standard output.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • 12
    but what are wide characters any way? – Whizz Mirray Sep 01 '15 at 18:29
  • 17
    `char` is used for *narrow* strings, suitable for 7-bit ASCII and 8-bit ANSI. `wchar_t` is used for *wide* strings, aka Unicode strings. However, the size of `wchar_t` is not portable, on some systems it is 16bit (suitable for UCS2/UTF-16), on others it is 32bit (suitable for UCS4/UTF-32). C++11 introduced new `char16_t` and `char32_t` types to deal with that descrepency. – Remy Lebeau Sep 01 '15 at 18:33
  • Does cout and wcout have their own buffer ? – name-1001 Dec 26 '22 at 11:28
  • @xusisme I would guess they’d have different buffers as they store characters of different types and the `std::basic_streambuf` abstraction doesn’t handle chatacter encodings on this level. I don’t think there is defined synchronization between the narrow and wide character streams, i.e., alternately writing to each if them may cause blocks of characters being written, although with `std::ios_base::sync_with_stdio(true)` (the default) the characters are still not buffered. – Dietmar Kühl Dec 26 '22 at 15:24
  • @DietmarKühl So, what happens if I mix cout and wcout ? – name-1001 Dec 27 '22 at 01:56
  • @xusisme: as I said: I don't thin there is a defined order between them. If `sync_with_stdio(false)` was called, I would expect characters to be emitted in blocks from `std::cout` and `std::wcout`. With `sync_with_stdio(true)` the same may happen but I would guess that for most implementations things interleave the way they are written as `sync_with_stdio(true)` typically disables buffering of the standard streams. – Dietmar Kühl Dec 27 '22 at 17:03
6

Another thing is that both are used with respected input stream.

Objects of these are initialized during or before the first time an object of std::ios_base::Init is created.

  • std::cout is std::basic_ios::tie'd to std::cin and to std::cerr
  • std:wcout is std::basic_ios::tie'd to std::wcin and to std::wcerr
oguzhan
  • 193
  • 9