C++中UTF-8与GBK转换需借助系统API或第三方库。Windows下可用MultiByteToWideChar和WideCharToMultiByte进行编码转换,分别实现UTF-8转GBK与GBK转UTF-8;跨平台推荐使用iconv库,支持多种编码,通过iconv_open、iconv等函数完成转换;也可使用Boost.Locale库的conv模块,调用to_utf和from_utf实现便捷转换。建议根据平台选择合适方法,并处理转换失败情况,确保输入合法,测试覆盖中文及特殊字符。

在C++中进行UTF-8和GBK编码转换,由于标准库不直接支持多字节编码转换,需要借助系统API或第三方库来实现。以下是几种常用且有效的方法。
使用Windows API进行转换
在Windows平台上,可以使用MultiByteToWideChar和WideCharToMultiByte函数完成UTF-8与GBK(代码页936)之间的转换。UTF-8 转 GBK 示例:
#include#include std::string utf8_to_gbk(const std::string& utf8) { int len = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0); std::wstring wstr(len, 0); MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wstr[0], len);
len = WideCharToMultiByte(936, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr); std::string gbk(len - 1, 0); WideCharToMultiByte(936, 0, wstr.c_str(), -1, &gbk[0], len, nullptr, nullptr); return gbk;}
GBK 转 UTF-8 示例:
立即学习“C++免费学习笔记(深入)”;
std::string gbk_to_utf8(const std::string& gbk) {
int len = MultiByteToWideChar(936, 0, gbk.c_str(), -1, nullptr, 0);
std::wstring wstr(len, 0);
MultiByteToWideChar(936, 0, gbk.c_str(), -1, &wstr[0], len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string utf8(len - 1, 0);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8[0], len, nullptr, nullptr);
return utf8;
}
使用iconv库(跨平台推荐)
在Linux或macOS上,或者希望代码跨平台,推荐使用iconv库。它支持多种编码转换。安装 iconv:
Ubuntu/Debian: sudo apt-get install libiconv-dev
macOS (with Homebrew): brew install libiconv
示例代码(GBK 转 UTF-8):
电子手机配件网站源码是一个响应式的织梦网站模板,软件兼容主流浏览器,且可以在PC端和手机端中进行浏览。模板包含安装说明,并包含测试数据。本模板基于DEDECms 5.7 UTF-8设计,需要GBK版本的请自己转换。模板安装方法:1、下载最新的织梦dedecms5.7 UTF-8版本。2、解压下载的织梦安装包,得到docs和uploads两个文件夹,请将uploads里面的所有文件和文件夹上传到你的
#include#include #include std::string gbk_to_utf8_iconv(const std::string& in) { iconv_t cd = iconv_open("UTF-8", "GBK"); if (cd == (iconv_t)-1) return "";
size_t in_len = in.size(); size_t out_len = in_len * 4; std::string out(out_len, 0); char* in_buf = const_castzuojiankuohaophpcnchar*youjiankuohaophpcn(in.c_str()); char* out_buf = &out[0]; size_t ret = iconv(cd, &in_buf, &in_len, &out_buf, &out_len); iconv_close(cd); if (ret == (size_t)-1) return ""; out.resize(out.size() - out_len); return out;}
同理可将"UTF-8"和"GBK"互换实现UTF-8转GBK。
使用第三方库:UTF8-CPP 或 Boost.Locale
对于更复杂的场景,可以考虑使用Boost.Locale,它封装了底层转换逻辑,支持格式化、本地化等。Boost.Locale 示例:
#include#include std::string gbk_to_utf8_boost(const std::string& gbk) { return boost::locale::conv::to_utf
(gbk, "GBK"); } std::string utf8_to_gbk_boost(const std::string& utf8) { return boost::locale::conv::from_utf
(utf8, "GBK"); }
需要链接 Boost.System 和 Boost.Locale 库。
基本上就这些常见方法。Windows下用API最直接,跨平台建议用iconv或Boost。注意处理转换失败的情况,确保输入字符串合法。编码转换虽小但容易出错,测试时多覆盖中文、特殊符号等用例。










