#include <iostream> #include <stdlib.h> #include <string.h> #include <string> #ifdef _WIN32 #include <Windows.h> #else #include <iconv.h> #endif #ifdef _WIN32 std::string Utf8ToGbk(const char* src_str) { std::string result; wchar_t* strSrc; char* szRes; int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0); strSrc = new wchar_t[len + 1]; MultiByteToWideChar(CP_UTF8, 0, src_str, -1, strSrc, len); len = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL); szRes = new char[len + 1]; WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, len, NULL, NULL); result = szRes; if(strSrc) delete[]strSrc; if(szRes) delete[]szRes; return result; } std::string GbkToUtf8(const char* src_str) { std::string result; wchar_t* strSrc; char* szRes; int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0); strSrc = new wchar_t[len + 1]; MultiByteToWideChar(CP_ACP, 0, src_str, -1, strSrc, len); len = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL); szRes = new char[len + 1]; WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, szRes, len, NULL, NULL); result = szRes; if (strSrc) delete[]strSrc; if (szRes) delete[]szRes; return result; } #else int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen) { iconv_t cd; int rc; char **pin = &inbuf; char **pout = &outbuf; cd = iconv_open(to_charset, from_charset); if (cd == 0) return -1; memset(outbuf, 0, outlen); if (iconv(cd, pin, &inlen, pout, &outlen) == -1) return -1; iconv_close(cd); return 0; } int GbkToUtf8(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen); } int Utf8ToGbk(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen); } #endif int main() { std::string teststr = "测试字符串"; std::cout << "原始字符串:" << teststr.c_str() << std::endl; #ifdef _WIN32 std::cout << Utf8ToGbk(GbkToUtf8(teststr.c_str()).c_str()) << std::endl; #else char result_g[1024]; GbkToUtf8((char*)teststr.c_str(), strlen(teststr.c_str()), result_g, 1024); char result_u[1024]; Utf8ToGbk(result_g, strlen(result_g), result_u, 1024); std::cout << result_g << std::endl; std::cout << result_u << std::endl; #endif return 0; }
转自:C++实现uft8和gbk编码字符串互相转换_std::string 转码gbk_baozhatoudale的博客-CSDN博客