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

前端 未结 3 503
南旧
南旧 2021-01-03 00:16

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

相关标签:
3条回答
  • 2021-01-03 00:20

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

    0 讨论(0)
  • 2021-01-03 00:28

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 00:39

    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);
    
    0 讨论(0)
提交回复
热议问题