What is the difference between std::cout and std::wcout?
Asked Answered
A

2

25

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 ?

Annecorinne answered 1/9, 2015 at 18:23 Comment(2)
The w versions of standard streams are for wide characters.Doradorado
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".Magalimagallanes
C
32

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.

Cosmo answered 1/9, 2015 at 18:26 Comment(6)
but what are wide characters any way?Annecorinne
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.Ruthenious
Does cout and wcout have their own buffer ?Laing
@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.Lefthand
@DietmarKühl So, what happens if I mix cout and wcout ?Laing
@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.Lefthand
B
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
Balsam answered 2/9, 2015 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.