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

2

9

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.

Stadtholder answered 25/11, 2009 at 18:37 Comment(2)
Keep in mind that even if you send the proper bytes for UTF-8/16, there's no guarantee that the users' tty supports unicode, or even if it does, that it has a font that has these characters in it.Varityper
My problem is how to send the proper bytes :) My terminal supports unicode characters, and for now I don't really care if it's going to be OK in another environment.Stadtholder
E
9

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.

Entomo answered 25/11, 2009 at 19:14 Comment(2)
In gnome go to Edit->Profile preferences, then under the General tab make sure that the font you are using supports special characters. Monospace will probably not work, however a font like DejaVu Sans Mono or Droid Sans Mono will.Cavalierly
Note: For me, I only needed setlocale(LC_ALL, "en_US.UTF-8"); Then, I could use even raw wchar_t characters.Indwell
U
4

Sorry misunderstood your question at first. This code prints a white king in terminal (tested it with KDE Konsole)

#include <iostream>

int main(int argc, char* argv[])
{
std::cout <<"\xe2\x99\x94"<<std::endl;
return 0;
}

Normally encoding is specified through a locale. Try to set environment variables.

In order to tell applications to use UTF-8 encoding, and assuming U.S. English is your preferred language, you could use the following command:

export LC_ALL=en_US.UTF-8

Are you using a "bare" terminal or something running under X-Server?

Unalterable answered 25/11, 2009 at 18:42 Comment(3)
I'm using a bash terminal on Ubuntu 8.04 and it's definitely supports unicode symbols.Stadtholder
Sorry, misunderstood your question at first. Changed my answer to reflect it.Unalterable
Thanks.. it's another solution, but I can only accept one answer!Stadtholder

© 2022 - 2024 — McMap. All rights reserved.