在c++中转换UTF-8与GBK编码需借助第三方库或系统API。windows平台可使用MultiByteToWidechar和WideCharToMultiByte,先转Unicode再互转;跨平台可用iconv库,通过code_convert函数实现;推荐使用Boost.Locale,提供简洁接口并支持多后端。

在C++中进行UTF-8和GBK编码转换,由于标准库不直接支持这些编码格式,需要借助第三方库或调用系统API来实现。以下是几种常见且实用的方法。
使用windows API进行转换
在Windows平台上,可以使用MultiByteToWideChar和WideCharToMultiByte函数完成UTF-8与GBK之间的转换。基本思路是:先将UTF-8转为Unicode(UTF-16),再从Unicode转为GBK,反之亦然。
UTF-8 转 GBK 示例代码:
// UTF-8 转 GBK std::String utf8_to_gbk(const std::string& utf8) { int len = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 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, NULL, 0, NULL, NULL); std::string gbk(len - 1, 0); WideCharToMultiByte(936, 0, wstr.c_str(), -1, &gbk[0], len, NULL, NULL); return gbk;
}
GBK 转 UTF-8 示例代码:
// GBK 转 UTF-8 std::string gbk_to_utf8(const std::string& gbk) { int len = MultiByteToWideChar(936, 0, gbk.c_str(), -1, NULL, 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, NULL, 0, NULL, NULL); std::string utf8(len - 1, 0); WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8[0], len, NULL, NULL); return utf8;
}
使用iconv库(跨平台方案)
iconv是gnu提供的字符集转换库,支持多种编码,在linux和macOS上原生支持,Windows可通过MinGW或libiconv引入。
编译时需链接libiconv:
立即学习“C++免费学习笔记(深入)”;
g++ main.cpp -liconv
示例代码(UTF-8 转 GBK):
#include <iconv.h>
std::string code_convert(const std::string& source_str, const char from_charset, const char to_charset) {
iconv_t cd = iconv_open(to_charset, from_charset);
if (cd == (iconv_t)-1) return “”;
size_t in_len = source_str.length(); size_t out_len = in_len * 4; std::string result(out_len, 0); char* in_buf = const_cast<char*>(source_str.c_str()); char* out_buf = &result[0]; size_t ret = iconv(cd, &in_buf, &in_len, &out_buf, &out_len); iconv_close(cd); if (ret == (size_t)-1) return ""; result.resize(result.size() - out_len); return result;
}
// 使用方式
std::string utf8_str = “你好”;
std::string gbk_str = code_convert(utf8_str, “UTF-8”, “GBK”);
使用Boost.Locale(推荐用于新项目)
Boost.Locale提供了简洁的接口进行编码转换,底层可基于ICU、iconv或WinAPI,适合跨平台开发。
示例:
#include <boost/locale.hpp>
std::string utf8_to_gbk_boost(const std::string& utf8) {
return boost::locale::conv::to_utf
// 或使用 conv::from_utf 转换方向
}
需要链接Boost.System和Boost.Locale库。
基本上就这些常用方法。Windows下用API最方便,跨平台建议用iconv或Boost。注意处理中文字符时确保输入合法,避免乱码。


