2021年10月19日 星期二

在 Windows 的 Console 顯示 utf-8

在 C++ 程式編譯之字串 一文中提到在 Console 顯示 wchar_t 字串的方法,但在 Windows 11 + MinGw 8.1.0 已經行不通了。不過現在比較流行用 UTF-8,若有在 Windows 的 Console 顯示 UTF-8 的須求,以下的方法很容易就能逹成

#include <iostream>
#include <Windows.h>
using namespace std;


int main(int, char**) 
{
  // Set console code page to UTF-8 so console known how to interpret string data
  SetConsoleOutputCP(CP_UTF8);

  // Enable buffering to prevent VS from chopping up UTF-8 byte sequences
  setvbuf(stdout, nullptr, _IOFBF, 1000);

  const char *str = u8"你好 こんにちは 안녕하십니까";

  cout << "str = " << str << endl;


  return 0;
}