Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display unicode characters in a linux terminal using C++?

I'm working on a chess game in C++ on a linux environment and I want to display the pieces using unicode characters in a bash terminal. Is there any way to display the symbols using cout?

An example that outputs a knight would be nice: ♞ = U+265E.

like image 659
Lipis Avatar asked Nov 25 '09 18:11

Lipis


1 Answers

To output Unicode characters you just use output streams, the same way you would output ASCII characters. You can store the Unicode codepoint as a multi-character string:

 std::string str = "\u265E";
 std::cout << str << std::endl;

It may also be convenient to use wide character output if you want to output a single Unicode character with a codepoint above the ASCII range:

 setlocale(LC_ALL, "en_US.UTF-8");
 wchar_t codepoint = 0x265E;
 std::wcout << codepoint << std::endl;

However, as others have noted, whether this displays correctly is dependent on a lot of factors in the user's environment, such as whether or not the user's terminal supports Unicode display, whether or not the user has the proper fonts installed, etc. This shouldn't be a problem for most out-of-the-box mainstream distros like Ubuntu/Debian with Gnome installed, but don't expect it to work everywhere.

like image 111
Charles Salvia Avatar answered Sep 20 '22 09:09

Charles Salvia