简体   繁体   中英

C++ unicode characters in console using printf?

My code:

#include <iostream>
#include <windows.h>

using namespace std;

int pos[9];

int main() {
    printf(" %c ║ %c ║ %c ", pos[0], pos[1], pos[2]);
    printf("═══╬═══╬═══");
    printf(" %c ║ %c ║ %c "), pos[3], pos[4], pos[5];
    printf("═══╬═══╬═══");
    printf(" %c ║ %c ║ %c "), pos[6], pos[7], pos[8];
    system("pause");
}

My console output:

安慰

I know there are other ways of doing this, but the point was to achieve this with printf :| Any ideas?

To use printf , and assuming you are using US-localized Windows with a console code page of 437 (run chcp to check), then the following corrected code will work if you save the source file in code page 437. One way to do this is to use Notepad++ and set Encoding->Character sets->Western European->OEM-US on the menu. The downside to this is your source code won't display nicely in most editors, unless they specifically support cp437, and even Notepad++ won't display it correctly on re-opening the file without setting the encoding again.

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    char pos[9] = {'X','O','X','O','X','O','X','O','X'};
    printf(" %c ║ %c ║ %c \n", pos[0], pos[1], pos[2]);
    printf("═══╬═══╬═══\n");
    printf(" %c ║ %c ║ %c \n", pos[3], pos[4], pos[5]);
    printf("═══╬═══╬═══\n");
    printf(" %c ║ %c ║ %c \n", pos[6], pos[7], pos[8]);
    system("pause");    system("pause");
}

On Windows, since the API is natively UTF-16, a better way is to use the following code and save the file in UTF-8 w/ BOM:

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    char pos[9] = {'X','O','X','O','X','O','X','O','X'};
    _setmode(_fileno(stdout), _O_U16TEXT);
    wprintf(L" %C ║ %C ║ %C \n", pos[0], pos[1], pos[2]);
    wprintf(L"═══╬═══╬═══\n");
    wprintf(L" %C ║ %C ║ %C \n", pos[3], pos[4], pos[5]);
    wprintf(L"═══╬═══╬═══\n");
    wprintf(L" %C ║ %C ║ %C \n", pos[6], pos[7], pos[8]);
    system("pause");
}

Output (both cases):

 X ║ O ║ X
═══╬═══╬═══
 O ║ X ║ O
═══╬═══╬═══
 X ║ O ║ X
Press any key to continue . . .

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