c++ convert windows 1252 to utf 8

您可以使用 Windows API 函数 MultiByteToWideChar 将 Windows 1252 编码的字符串转换为 UTF-16LE 编码形式的宽字符串,然后再使用 WideCharToMultiByte 函数将宽字符串转换为 UTF-8 编码的字符串。

以下是一个使用这两个函数实现字符串转换的示例代码:

#include <Windows.h>
#include <string>
std::string ConvertWindows1252ToUTF8(const std::string &src) {
  int size = MultiByteToWideChar(1252, 0, src.c_str(), -1, nullptr, 0);
  wchar_t *wide = new wchar_t[size];
  MultiByteToWideChar(1252, 0, src.c_str(), -1, wide, size);
  int utf8Size = WideCharToMultiByte(CP_UTF8, 0, wide, -1, nullptr, 0, nullptr, nullptr);
  char *utf8 = new char[utf8Size];
  WideCharToMultiByte(CP_UTF8, 0, wide, -1, utf8, utf8Size, nullptr, nullptr);
  std::string result(utf8);
  delete[] wide;
  delete[] utf8;
  return result;

希望这些信息能对您有所帮助。

  •