In chapter 7 in our book, Learning C++, (which is on sale – 45% discount only on May 13th), we demonstrate how to display UNICODE text in Console applications. It was challanging for several reasons:
- Different requirements and support in Windows Vs. Linux and MacOSX.
- Console apps tends to lack the ability to show right-to-left languages correcty.
- Console apps and terminals are limited when it comes to the ability to print different fonts, enoding, etc.
As explained in my Stackoverflow answer, I used preproesssor diretive ti distinguish between Windows and Linux / MacOSX, and used “אבא” (Dad, in Hebrew), which is a palindromes in Hebrew to solve the revered text issue.
#include <iostream>
#ifdef _WIN32 // #A
#include <io.h> // #B
#include <fcntl.h> // #C
#else // #D
#include <locale> // #E
#endif
int main()
{
#ifdef _WIN32 // #A
_setmode(_fileno(stdout), _O_U16TEXT); // #F
std::wcout << L"אבא" << std::endl; // #G
#else // #D
std::locale::global(std::locale("")); // #H
std::wcout.imbue(std::locale()); // #I
std::wcout << L"אבא" << std::endl; // #G
#endif
}
Here are the annotations of the code:
A – Preprocessor directive for Windows-specific code
B – Include the io.h library for low-level I/O operations
C – Include the fcntl.h library for file control operations
D – Preprocessor directive for non-Windows code
E – Include the locale library for locale-specific operations
F – Set the mode of stdout to use Unicode
G – Print the Hebrew word to the console
H – Set the global locale to the user’s preferred locale
I – Set the locale of wcout to the global locale