What is the difference between std::cout and std::wcout?
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 ?
2 Answers 2
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.
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
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.8.1.43553
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
std:: wcout
Object of class wostream that represents the standard output stream oriented to wide characters (of type wchar_t ). It corresponds to the C stream stdout .
The is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as wcerr or wclog ).
As an object of a basic_ostream class, characters can be written to it either as formatted data using the insertion operator ( operator<< ) or as unformatted data, using member functions such as write .
The object is declared in header <iostream> with external linkage and static duration: it lasts the entire duration of the program.
wcout is not tied to any other output stream (see basic_ios::tie ).
By default, wcout is synchronized with stdout (see ios_base::sync_with_stdio ).
A program should not mix output operations on wcout with output operations on cout (or with other narrow-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 .
For more information on the operations supported by wcout , see the reference for its type: basic_ostream .
std:: cout, std:: wcout
The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf ), associated with the standard C output stream stdout .
These objects are guaranteed to be initialized during or before the first time an object of type std::ios_base::Init is constructed and are available for use in the constructors and destructors of static objects with ordered initialization (as long as <iostream> is included before the object is defined).
Unless std :: ios_base :: sync_with_stdio ( false ) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output.
By specification of std::cin , std:: cin . tie ( ) returns & std :: cout . This means that any input operation on std::cin executes std :: cout . flush ( ) (via std::basic_istream::sentry ‘s constructor). Similarly, std:: wcin . tie ( ) returns & std :: wcout .
By specification of std::cerr , std:: cerr . tie ( ) returns & std :: cout . This means that any output operation on std::cerr executes std :: cout . flush ( ) (via std::basic_ostream::sentry ‘s constructor). Similarly, std:: wcerr . tie ( ) returns & std :: wcout . (since C++11)
[edit] Notes
The ‘c’ in the name refers to «character» (stroustrup.com FAQ); cout means «character output» and wcout means «wide character output».
Because dynamic initialization of templated variables are unordered, it is not guaranteed that std::cout has been initialized to a usable state before the initialization of such variables begins, unless an object of type std::ios_base::Init has been constructed.
std::cout, std::wcout
Глобальные объекты std::cout и std::wcout управляют выводом в буфер потока типа, определяемого реализацией (производного от std::streambuf ), связанного со стандартным потоком вывода C stdout .
Эти объекты гарантированно будут инициализированы во время или до первого создания объекта типа std::ios_base::Init и доступны для использования в конструкторах и деструкторах статических объектов с упорядоченной инициализацией (пока <iostream> > включается до определения объекта).
Если не std::ios_base::sync_with_stdio(false) , можно безопасно одновременно обращаться к этим объектам из нескольких потоков как для форматированного, так и для неформатированного вывода.
По спецификации std::cin std::cin.tie() .tie std::cin.tie() возвращает &std::cout . Это означает, что любая операция ввода в std::cin выполняет std::cout.flush() (через std::basic_istream::sentry ). Точно так же std::wcin.tie() возвращает &std::wcout .
По спецификации std::cerr std std::cerr.tie() возвращает &std::cout . Это означает, что любая операция вывода на std::cerr выполняет std::cout.flush() (через std::basic_ostream::sentry ). Точно так же std::wcerr.tie() возвращает &std::wcout . (начиная с С++ 11).
Notes
Буква «c» в названии означает «персонаж» ( stroustrup.com FAQ ); cout означает «вывод символов», а wcout означает «вывод широких символов».
Поскольку динамическая инициализация шаблонных переменных неупорядочена, не гарантируется, что std::cout будет инициализирован в пригодном для использования состоянии до начала инициализации таких переменных, если только не был создан объект типа std::ios_base::Init .