0

I am trying to print a "pawn" while using visual studio and it doesn't recognize the unicode.

can anyone tell me how to fix it?

this is a basic example:

#include <iostream>

using namespace std;

int main()
{
 cout << "\33[37;42m\u2659\33[0m";
}

and the output i get is:

"<-[37;42m?<-[0m".

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31

1 Answers1

3

The ordinary Windows console windows do not support ANSI escape sequences.

To display general Unicode characters you can

  • use the Windows console functions instead, or

  • set up standard data streams to Unicode (Microsoft extension, see _setmode) and use wide streams, or

  • e.g. display a text file with the desired text, e.g. encoded in UCS-2.


Example 1: Using the Windows console functions.

Code:

#undef UNICODE
#define UNICODE
#include <windows.h>

#include <string>

namespace console {
    using std::wstring;

    const HANDLE output = GetStdHandle( STD_OUTPUT_HANDLE );

    void write( const wstring& text )
    {
        if( text.length() == 0 ) { return; }
        DWORD n_chars_written = 0;
        WriteConsole( output, &text[0], text.length(), &n_chars_written, 0 );
    }
}

auto main() -> int
{
    console::write( L"Oh look, a \u2659!\n" );
}

Running this in the ordinary Windows console will most likely produce a square instead of a pawn symbol, even in Windows 8.x with e.g. Lucida Console font. That’s because the console window implementation simply does not support presentation of such characters. The character is correctly stored, and you can copy it out and e.g. present it in Windows Write (standard accessory program), but that’s a tad impractical, shall we say, for the ordinary end user.

A simple solution is to require use of e.g. the Console console window replacement.

Then you get nifty tabs, too. ;-)

H:\dev\test\so\0208>g++ using_console_api.cpp

H:\dev\test\so\0208>a
Oh look, a ♙!

H:\dev\test\so\0208>_

Example 2: using wide streams.

Code:

#include <assert.h>
#include <iostream>

#include <fcntl.h>      // _O_WTEXT
#include <io.h>         // _setmode, _isatty

namespace console {
    struct Usage
    {
        Usage()
        {
            const int out_fileno = _fileno( stdout );

            assert( _isatty( out_fileno ) );
            _setmode( out_fileno, _O_WTEXT );
        }
    };
}  // console

const console::Usage console_usage;

auto main() -> int
{
    using namespace std;
    wcout << L"Oh look, a \u2659!" << endl;
}

I recall that at one time, probably with the original MinGW g++, one had to define some special preprocessor symbol to get the Microsoft library extensions defined. However, this compiled nicely as-is with MinGW g++ 4.9.1 from the Nuwen distribution. And of course, it also compiles nicely with Visual C++.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331