Garbled characters appearing in the console output of a C program are usually caused by a mismatch between the program's output encoding and the console's parsing encoding.

The following code outputs garbled characters in the Windows console, likely because the console's default encoding is GBK, while the program outputs in UTF-8.

#include <stdio.h>

int main(){
	printf("你好\n");
}

Program Output

浣犲ソ

Check Console Encoding

Use the command chcp in the console to check;

chcp
Active Code Page: 936

The Active Code Page is the character encoding table currently used by the Windows console (CMD/PowerShell). It determines how the console interprets the bytes you input (keyboard input) and how it converts internal bytes into characters displayed on the screen.

Code Page Name
437 OEM United States (default for English console)
936 GBK (default for Simplified Chinese Windows)
950 Big5 (Traditional Chinese Windows)
65001 UTF-8 (Unicode international standard)

Solutions for Garbled Characters

SetConsoleOutputCP(CP_UTF8) and SetConsoleCP(CP_UTF8) are Windows console-specific APIs used to set the console's input and output code pages to UTF-8. These functions are only effective on the Windows platform; Linux/macOS do not need them (they natively support UTF-8).

The value of CP_UTF8 is 65001; using them requires importing the windows.h header file;

#include <stdio.h>
#include <windows.h>

int main(){
    
    SetConsoleOutputCP(CP_UTF8);
    SetConsoleCP(CP_UTF8);

	printf("你好\n");

}

You can use GetConsoleOutputCP() to get the current terminal's output code page;

#include <stdio.h>
#include <windows.h>

int main() {
    UINT active_cp = GetConsoleOutputCP();  // Get output code page
    printf("%u\n", active_cp);
    return 0;
}

Temporary Method

Run the command chcp 65001 in the console to change the console's encoding to UTF-8;

This method is suitable for situations where the program cannot be recompiled.

Emoji or Rare Characters Displayed as Boxes

☐☐☐☐☐☐☐☐☐

This is because the font currently used by the console does not support these characters; you need to change the console's font;