中文編碼基礎
- GBK/GB2312:雙位元組編碼,每漢字 2 bytes,Windows 經典專案常用。
- UTF-8:變長編碼,漢字 3 bytes,現代跨平台標準。
- UTF-16 (wchar_t):Windows API 內部編碼,固定 2/4 bytes。
char 陣列儲存 GBK 中文
// GBK 環境下
char str1[] = "中"; // sizeof=3 (含 \0),實際 2 bytes 漢字 + \0
char str5[11] = "你好世界"; // 5 漢字 ×2 + \0 = 11 bytes
printf("%s", str5); // 終端機編碼需匹配 GBK 才能正確顯示
現代最佳實踐:UTF-8 + 寬字元 API
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, ""); // 啟用當前環境 locale (支援 UTF-8)
// 原始碼儲存為 UTF-8,使用 u8 前綴 (C11)
const char *utf8_str = u8"你好世界";
printf("UTF-8: %s\n", utf8_str);
// 寬字元字面值 L"" (編碼為編譯器執行字元集,通常 UTF-16/32)
const wchar_t *wstr = L"你好世界";
wprintf(L"Wide: %ls\n", wstr);
return 0;
}
Windows 主控台顯示中文關鍵設定
- 原始碼檔案 **儲存為 UTF-8 (含 BOM 或無 BOM)**。
- 編譯器指定原始碼編碼:GCC
-finput-charset=UTF-8,MSVC /source-charset:utf-8 (VS 2015+)。
- 執行時主控台代碼頁設為 UTF-8:
chcp 65001 或程式呼叫 SetConsoleOutputCP(65001)。
- 字型選擇支援中文的 TrueType 字型 (如 Consolas + YaHei Consolas Hybrid、Cascadia Code)。