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

在C++中进行UTF-8和GBK编码转换,由于标准库不直接支持这些编码格式,需要借助第三方库或调用系统API来实现。以下是几种常见且实用的方法。
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;
}
编译时需链接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");
示例:
#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。注意处理中文字符时确保输入合法,避免乱码。
以上就是c++++怎么进行UTF-8和GBK编码转换_c++ UTF-8/GBK编码转换方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号