VS下的中文显示问题-编码转换

  这是一个系列的文章,详情可点击关于这两年所经历项目的系列总结

  在VS2010下开发Cocos2dx项目,首先遇到的第一个问题是中文显示问题,这个前辈们已经给出了不错的答案了,这里贴一下自己项目中的代码。

1、主要的转换代码
int GBK2UTF8(std::string & gbkStr, const char* toCode, const char* fromCode)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	iconv_t iconvH;
	iconvH = iconv_open(fromCode, toCode);
	if (iconvH == 0)
	{
		return -1;
	}
	const char* strChar = gbkStr.c_str();
	const char** pin = &strChar;
	size_t strLength = gbkStr.length();
	if (strLength <= 0)
	{
		return -1;
	}
	char* outbuf = (char*) malloc(strLength*4);
	char* pBuff = outbuf;

	memset( outbuf, 0, strLength*4);
	size_t outLength = strLength*4;
	if (-1 == ::iconv(iconvH, pin, &strLength, &outbuf, &outLength))
	{
		iconv_close(iconvH);
		free(pBuff);
		return -1;
	}
	gbkStr = pBuff;
	free(pBuff);
	iconv_close(iconvH);
#else

#endif
	return 0;
}


2、GBK转UTF-8
std::string GBK2UTF8(const char* szMsg)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	std::string sztemp = "";
	sztemp.append(szMsg);
	GBK2UTF8(sztemp, "gb2312", "utf-8");
	return sztemp;
#else
	return szMsg;
#endif
}


3、UTF-8转GBK
std::string UTF8GBK2(const char* szMsg)
{
	if (szMsg == NULL || *szMsg == 0) return szMsg;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	std::string sztemp = "";
	sztemp.append(szMsg);
	GBK2UTF8(sztemp, "utf-8", "gb2312");
	return sztemp;
#else
	return szMsg;
#endif
}


由于在Mac OS X系统下不需要做这样的转换,因此这里加上了对WIN_32的判定。这样方法便可兼容Windows和Mac OS X系统了。

猜你喜欢

转载自lizi07.iteye.com/blog/2104498
今日推荐