c++转编码---UTF8转GBK---GBK转UTF8

编码转换

#include "iconv.h"

// 编码转换函数
static std::string encode_convert(const char* fromcode, const char* tocode, const char* text)
{
	char* tmp = (char*)text;
	size_t lenSrc = strlen(tmp);
	size_t lenDst = lenSrc * 5;
	char* out = (char*)malloc(lenDst);
	memset(out, 0, lenDst);
	char* pFreeOut = out;
	iconv_t cd = iconv_open(tocode, fromcode);
	size_t ret = iconv(cd, &tmp, &lenSrc, &out, &lenDst);
	if (ret == -1)
	{
		return "";
	}
	std::string retStr(pFreeOut);
	iconv_close(cd);
	free(pFreeOut);
	return retStr;
}

// GBK转utf-8
static std::string GBK_TO_UTF8(const char* text)
{
	if (strlen(text) == 0)
	{
		return "";
	}
	return encode_convert("GBK", "UTF-8", text);
}
// utf-8转GBK
static std::string UTF8_TO_GBK(const char* text)
{
	if (strlen(text) == 0)
	{
		return "";
	}
	return encode_convert("UTF-8", "GBK", text);
}


int main()
{
	std::string test = "测试";
	std::string GBK = UTF8_TO_GBK(test.c_str());

	std::cout << ": " << test << std::endl;
	std::cout << ": " << GBK << " size:" << GBK.size()<<std::endl;
}