-->

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

2019-02-10 00:25发布

问题:

I am fairly new to programming, but it seems like the π(pi) symbol is not in the standard set of outputs that ASCII handles.

I am wondering if there is a way to get the console to output the π symbol, so as to express exact answers regarding certain mathematical formulas.

回答1:

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);


回答2:

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()



回答3:

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;
}