一、windows下转换方法:
// 当type为CP_ACP时,GBK转化为UNICODE;当type为CP_UTF8时,UTF8转化为UNICODE
wchar_t* trans(const char * ch, int type = CP_ACP) {
int len = MultiByteToWideChar(type, 0, ch, -1, nullptr, 0);
wchar_t *str = new wchar_t[len + 1];
wmemset(str, 0, len + 1);
MultiByteToWideChar(type, 0, ch, -1, str, len);
return str;
}
// 当type为CP_ACP时,UNICODE转化为GBK;当type为CP_UTF8时,UNICODE转化为UTF8
char* trans(const wchar_t * wch, int type = CP_ACP) {
int len = WideCharToMultiByte(type, 0, wch, -1, nullptr, 0, nullptr, nullptr);
char *str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(type, 0, wch, -1, str, len, nullptr, nullptr);
return str;
}
注意:
转换后的字符串,使用之后,需要delete掉。
二、linux下转换方法:
bool trans(const char *pFromCode,const char *pToCode,const char *pInBuf,size_t iInLen,char *pOutBuf,size_t iOutLen)
{
//打开字符集转换
iconv_t hIconv = iconv_open(pToCode, pFromCode);
if (! hIconv) return false;
//开始转换
size_t iRet = iRet = iconv(hIconv, (char **) (&pInBuf), &iInLen, &pOutBuf, &iOutLen);
//关闭字符集转换
iconv_close(hIconv);
return (bool)iRet;
}
使用方法:
string result = "这是gbk字符串";
char ch[255];
memset(ch,'\0',sizeof(ch));
trans("GBK","UTF-8",result.c_str(),result.size(),ch,sizeof(ch));
注意:
需要安装libiconv的开发包,并引入头文件#include "iconv.h"
三、c++11自带的编码转换器,代码如下:
#include "stdafx.h"
#include #include #include using namespace std;
using WCHAR_GBK= codecvt_byname;
using WCHAR_UTF8= codecvt_utf8;
// linux下为"zh_CN.GBK"
#define GBK_NAME ".936"
int main()
{
// 定义一个utf8字符串
string result = u8"中国人";
// gbk与unicode之间的转换器
wstring_convertcvtGBK(new WCHAR_GBK(GBK_NAME));
// utf8与unicode之间的转换器
wstring_convertcvtUTF8;
// 从utf8转换为unicode
wstring ustr = cvtUTF8.from_bytes(result);
// 从unicode转换为gbk
string str = cvtGBK.to_bytes(ustr);
cout << str << endl;
getchar();
return 0;
}