C++控制台输出UTF-8乱码

找到了一个函数,打印时候用这个函数包装一下,把UTF-8格式转成GB2312格式就可以输出到控制台了。

static char* U2G(const char* utf8) {
  int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  wchar_t* wstr = new wchar_t[len + 1];
  memset(wstr, 0, len + 1);
  MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
  len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
  char* str = new char[len + 1];
  memset(str, 0, len + 1);
  WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
  if (wstr) delete[] wstr;
  return str;
}

下面这个方法试过,我这里无效,大家也可以参考试试:https://blog.csdn.net/hik_zxw/article/details/52789570

这个方法注意要改动一个地方,wcscpy不安全会报错,改成wcscpy_s就可以了。

猜你喜欢

转载自blog.csdn.net/weixin_42165585/article/details/81385047