C++ string字符串的UTF-8与GBK(GB2312)编码相互转换转换

  • Post author:
  • Post category:其他


C++ 试用strcpy读取中文路径时存在乱码,进行utf-8编码到gbk编码的转换后问题解决。

原文链接:


link

.

原文代码:

#pragma once

#include <iostream>

#include <string>

#include <fstream>

#include <windows.h>
/*
UTF-8 转 GBK
*/
static std::string UTF8ToGBK(const char* strUTF8)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
    wchar_t* wszGBK = new wchar_t[len + 1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, wszGBK, len);
    len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
    char* szGBK = new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
    std::string strTemp(szGBK);
    if (wszGBK) delete[] wszGBK;
    if (szGBK) delete[] szGBK;
    return strTemp;
}

————————————————

版权声明:本文为CSDN博主「晚归」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/FK2016/article/details/82226683