答案:在C++中转换UTF-8到GBK编码,Windows平台可使用MultiByteToWideChar和WideCharToMultiByte函数,先将UTF-8转为UTF-16再转为GBK;跨平台则推荐使用iconv库,通过iconv_open、iconv和iconv_close实现转换,需注意缓冲区大小及编码兼容性问题。

在C++中将UTF-8编码转换为GBK编码,可以使用Windows平台的API函数或跨平台的开源库(如iconv)。以下是两种常见实现方式:
1. Windows平台使用MultiByteToWideChar和WideCharToMultiByte
Windows提供了两个关键API:- MultiByteToWideChar:将UTF-8转为Unicode(UTF-16)
- WideCharToMultiByte:将Unicode转为GBK(代码页936)
示例代码:
#include <windows.h>
#include <string>
<p>std::string UTF8ToGBK(const std::string& utf8Str) {
if (utf8Str.empty()) return {};</p><pre class='brush:php;toolbar:false;'>// 第一步:UTF-8 转 Unicode
int wLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, nullptr, 0);
if (wLen == 0) return {};
std::wstring wstr(wLen, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &wstr[0], wLen);
// 第二步:Unicode 转 GBK
int gbkLen = WideCharToMultiByte(936, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (gbkLen == 0) return {};
std::string gbkStr(gbkLen, 0);
WideCharToMultiByte(936, 0, wstr.c_str(), -1, &gbkStr[0], gbkLen, nullptr, nullptr);
// 去除末尾多余的\0
if (!gbkStr.empty() && gbkStr.back() == '\0') {
gbkStr.pop_back();
}
return gbkStr;}
2. Linux/跨平台使用iconv库
在Linux或macOS上,推荐使用libiconv进行编码转换。安装iconv(Ubuntu为例):
立即学习“C++免费学习笔记(深入)”;
sudo apt-get install libiconv-dev
使用示例:
#include <iconv.h>
#include <string>
#include <vector>
<p>std::string UTF8ToGBK(const std::string& utf8Str) {
iconv_t cd = iconv_open("GBK", "UTF-8");
if (cd == (iconv_t)-1) return {};</p><pre class='brush:php;toolbar:false;'>size_t inLen = utf8Str.size();
size_t outLen = inLen * 2;
std::vector<char> outBuf(outLen);
char* inPtr = const_cast<char*>(utf8Str.data());
char* outPtr = outBuf.data();
size_t ret = iconv(cd, &inPtr, &inLen, &outPtr, &outLen);
iconv_close(cd);
if (ret == (size_t)-1) return {};
return std::string(outBuf.data(), outPtr - outBuf.data());}
注意事项
- 中文字符在GBK中通常占2字节,在UTF-8中占3字节,目标缓冲区要足够大
- Windows代码页936即GBK编码,支持大部分中文字符
- 某些生僻字可能在GBK中无对应编码,转换会失败或替换为问号
- 跨平台项目建议封装统一接口,根据编译环境选择实现
基本上就这些。Windows用系统API最方便,Linux用iconv更通用。











