简体   繁体   中英

Unicode doesn't output correctly (Windows 10)

I am a beginner programmer and I'm working on a simple game. I want to output Unicode symbols like Alt + 2 1 9 █ to the console. I am using CodeBlocks on Windows 10 and I am using GNU GCC compiler. Here is what I'm trying to do:

#include <iostream>

using namespace std;

int main()
{
    cout << "\u2588";
    return 0;
}

What I get on console is a few strange symbols. This happens even with other Unicode characters, but the symbols are different.

I tried using wcout , but then i get just a blank space instead.

I also tried things like this:

_setmode(_fileno(stdout), _O_U16TEXT);

But then I get errors that _fileno and _O_U16TEXT was not declared, though I imported the libraries that seem to be necessary for this:

#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>

The Unicode symbols are not totally necessary for my game, but I just want it look nicer.

That's because you're trying to print wchar_t (16 bits long) characters with std::cout that only supports char (8 bits long). Use std::wcout instead of std::cout , wcout is meant for wide characters.

The Windows Command Prompt uses CP850 as encoding by default, and won't be able to correctly display this symbol or any Unicode symbol for that matter unless you change it .

It has, however, its own version of it, \\xDB that is probably what you are looking for.

For other symbols you can use in the Windows Command Prompt, open charmap.exe and check the font Terminal , there's a range of useful symbols that should be compatible with CP850 and display under the Command Prompt the same way they are presented there.

Other answers have addressed treating the string as a UTF-16 literal. You can also tell the compiler to treat it as a utf-8 literal (forcing it to encode all characters within it as utf-8) by prefixing it with u8 :

#include <iostream>

using namespace std;

int main()
{
    cout << u8"\u2588";
    return 0;
}

Note that windows consoles aren't by default set to treat output as utf-8, so this still won't display correctly without some additional settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM