何问起C++教程 - Windows编程 - Win32编程
C++ 中文乱码的问题解决办法
乱码的根本原因就是字符串编码的方式,以及字符串解码方式不一致导致的, 而在我们平常用的编码解码方式一般都是utf-8以gbk之间的相互转换, 下面给出编码方式的转换c++方法的代码:
#include <Windows.h>
#include <string>

using namespace std;

string HtUtfToString(string strValue)
{

int m_hovertreenwLen = ::MultiByteToWideChar(CP_ACP, 0, strValue.c_str(), -1, NULL, 0);
wchar_t * pwBuf = new wchar_t[m_hovertreenwLen + 1];//加上末尾'\0'
ZeroMemory(pwBuf, m_hovertreenwLen * 2 + 2);
::MultiByteToWideChar(CP_ACP, 0, strValue.c_str(), strValue.length(), pwBuf, m_hovertreenwLen);
//int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, 0, NULL, NULL);
char * pBuf = new char[nLen + 1];
ZeroMemory(pBuf, nLen + 1);
::WideCharToMultiByte(CP_UTF8, 0, pwBuf, m_hovertreenwLen, pBuf, nLen, NULL, NULL);
std::string m_hovertreeReturnStr(pBuf);
delete []pwBuf;
delete []pBuf;
pwBuf = NULL;
pBuf = NULL;
return m_hovertreeReturnStr;
}

//乱码的根本原因就是字符串编码的方式也字符串解码方式不一致导致的, 而在我们平常用的编码编码方式一般都是utf-8以gbk之间的相互转换, 下面给出编码方式的转换代码
string HtStringToUtf(string strValue)
{

int m_hovertreenwLen = MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), -1, NULL, 0);
wchar_t * pwBuf = new wchar_t[m_hovertreenwLen + 1];//加上末尾'\0'
memset(pwBuf, 0, m_hovertreenwLen * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), strValue.length(), pwBuf, m_hovertreenwLen);
//int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);//这句在编译时会出现警告
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, 0, NULL, NULL);
char * pBuf = new char[nLen + 1];
memset(pBuf, 0, nLen + 1);
WideCharToMultiByte(CP_ACP, 0, pwBuf, m_hovertreenwLen, pBuf, nLen, NULL, NULL);
std::string m_hovertreeReturnStr = pBuf;
delete []pBuf;
delete []pwBuf;
return m_hovertreeReturnStr;

}

string HtUtfToGbk(string strValue)
{
int m_hovertreeLen = MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), -1, NULL, 0);
wchar_t* wstr = new wchar_t[m_hovertreeLen+1];
memset(wstr, 0, m_hovertreeLen+1);
MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), -1, wstr, m_hovertreeLen);
m_hovertreeLen = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[m_hovertreeLen+1];
memset(str, 0, m_hovertreeLen+1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, m_hovertreeLen, NULL, NULL);
if(wstr) delete[] wstr;
return string(str);
}

当string中包含中文,如果要转为LPCSTR,可以先StringToUtf方法处理一下再转,则可以避免乱码。
收藏 列表

评论: