Output unicode symbol π and ≈ in c++ win32 console application

依然范特西╮ 提交于 2019-11-30 14:18:27

I'm not really sure about any other methods (such as those that use the STL) but you can do this with Win32 using WriteConsoleW:

HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
LPCWSTR lpPiString = L"\u03C0";

DWORD dwNumberOfCharsWritten;
WriteConsoleW(hConsoleOutput, lpPiString, 1, &dwNumberOfCharsWritten, NULL);

The Microsoft CRT is not very Unicode-savvy, so it may be necessary to bypass it and use WriteConsole() directly. I'm assuming you already compile for Unicode, else you need to explicitly use WriteConsoleW()

I'm in the learning phase of this, so correct me if I get something wrong.

It seems like this is a three step process:

  1. Use wide versions of cout, cin, string and so on. So: wcout, wcin, wstring
  2. Before using a stream set it to an Unicode-friendly mode.
  3. Configure the targeted console to use an Unicode-capable font.

You should now be able to rock those funky åäös.

Example:

#include <iostream>
#include <string>
#include <io.h>

// We only need one mode definition in this example, but it and several other
// reside in the header file fcntl.h.

#define _O_WTEXT        0x10000 /* file mode is UTF16 (translated) */
// Possibly useful if we want UTF-8
//#define _O_U8TEXT       0x40000 /* file mode is UTF8  no BOM (translated) */ 

void main(void)
{
    // To be able to write UFT-16 to stdout.
    _setmode(_fileno(stdout), _O_WTEXT);
    // To be able to read UTF-16 from stdin.
    _setmode(_fileno(stdin), _O_WTEXT);

    wchar_t* hallå = L"Hallå, värld!";

    std::wcout << hallå << std::endl;

      // It's all Greek to me. Go UU!
    std::wstring etabetapi = L"η β π";

    std::wcout << etabetapi << std::endl;

    std::wstring myInput;

    std::wcin >> myInput;

    std:: wcout << myInput << L" has " << myInput.length() << L" characters." << std::endl;

    // This character won't show using Consolas or Lucida Console
    std::wcout << L"♔" << std::endl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!