5

How I print these UTF-8 characters in C++?

3
  • 1
    depends on what font you use, whether it's unix or windows, whether you are writing a console or a GUI api. Commented Jan 23, 2010 at 5:29
  • preferably cross platform console Commented Jan 23, 2010 at 6:11
  • These characters aren't part of the ASCII character set, which means you have to select a font that contains them before you can print them. There is no cross platform way to select fonts for console apps. I don't think you can do it at all on Windows. Commented Jan 23, 2010 at 8:34

3 Answers 3

3

Just output the appropriate bytes to your terminal, and make sure the terminal is using a UTF-8 encoding to display your data. C++ itself is relatively UTF8-agnostic. It's just an array of uint_8's.

(Unless you want to use some sort of character-oriented operations on strings with UTF-8. Then you need to use UTF-8 manipulation functions, instead of array indexes and the normal string manipulation routines.)

e.g. sprintf("%c%c%c\n", 0xE2, 0x99, 0xA0);

Sign up to request clarification or add additional context in comments.

Comments

1

Well, you know it is possible because your browser could render them. On Windows you can use the charmap.exe applet to discover their Unicode code points:

  • ♠ = 0x2660
  • ♣ = 0x2663
  • ♥ = 0x2665
  • ♦ = 0x2666

The challenge is to get a C/C++ program to display them. That's not going to be possible in any kind of non-platform specific way unless you use a cross-platform UI library like Qt or wxWidgets. In a Windows GUI program you can do it like this in the WM_PAINT message handler:

 case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); HFONT hFont = CreateFont(16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Arial Unicode MS"); HGDIOBJ oldFont = SelectObject(hdc, hFont); RECT rc = {0, 0, 666, 16}; DrawTextEx(hdc, L"\x2660\x2663\x2665\x2666", -1, &rc, DT_LEFT, 0); SelectObject(hdc, oldFont); DeleteObject(hFont); EndPaint(hWnd, &ps); } break; 

Comments

0

In C++: std::wcout << L"wstr [" << wstr << L']' << std::endl;

In C: printf("%ls\n\n",wstr);

1 Comment

wchar_t isn't guaranteed to be UTF-16. It's certainly not going to be UTF-8.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.