C++ utf8转为gbk_C++ 字符串UTF8与GBK互相转化

UTF-8转为GBK2312代码

引入头文件

#include "windows.h"

代码

// UTF-8转为GBK2312

std::string UtfToGbk(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;

}

GBK转化为UTF8格式代码

代码

//GBK转化为UTF8格式

void ConvertGBKToUtf8(CString &strGBK)

{

int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);

wchar_t * wszUtf8 = new wchar_t [len];

memset(wszUtf8, 0, len);

MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, wszUtf8, len);

len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);

char *szUtf8=new char[len + 1];

memset(szUtf8, 0, len + 1);

WideCharToMultiByte (CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL,NULL);

strGBK = szUtf8;

delete[] szUtf8;

delete[] wszUtf8;

}
未经允许不得转载:紫竹林-程序员中文网 » C++ utf8转为gbk_C++ 字符串UTF8与GBK互相转化
关于我们 免责申明 意见反馈 隐私政策
程序员中文网:公益在线网站,帮助学习者快速成长!
关注微信 技术交流
推荐文章
每天精选资源文章推送
推荐文章
随时随地碎片化学习
推荐文章
发现有趣的