How to print UNICODE text in Console applications

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:

  1. Different requirements and support in Windows Vs. Linux and MacOSX.
  2. Console apps tends to lack the ability to show right-to-left languages correcty.
  3. 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

Unknown's avatar

About Michael Haephrati מיכאל האפרתי

Michael Haephrati is a music composer, an inventor and an expert specializes in software development and information security, who has built a unique perspective which combines technology and the end user experience. Author of Learning C++ https://www.manning.com/books/learning-c-plus-plus
This entry was posted in Uncategorized and tagged , , , , , , , . Bookmark the permalink.

Leave a comment