答案:C++中宽字符与多字节字符转换常用Windows API、标准库wstring_convert(已废弃)及第三方库如utf8cpp。Windows平台使用WideCharToMultiByte和MultiByteToWideChar实现高效转换;C++11至C++17可用wstring_convert配合codecvt进行UTF-8与wstring互转,但该方法在C++20被移除;现代项目推荐使用utf8cpp、ICU或Boost.Locale等跨平台库以确保兼容性与维护性。

在C++中处理宽字符(wchar_t)和多字节字符(如UTF-8或ANSI)之间的转换,常用的方法依赖于平台和编码格式。以下是几种实用且跨平台兼容性较好的转换方式。
宽字符转多字节(wchar_t → char)
将宽字符串转换为UTF-8或多字节字符串:#include <windows.h>
#include <string>
<p>std::string wstr_to_utf8(const std::wstring& wstr) {
if (wstr.empty()) return {};
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), nullptr, 0, nullptr, nullptr);
std::string str(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, nullptr, nullptr);
return str;
}
多字节转宽字符(char → wchar_t)
将UTF-8字符串转换为宽字符串:std::wstring utf8_to_wstr(const std::string& str) {
if (str.empty()) return {};
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), nullptr, 0);
std::wstring wstr(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstr[0], size_needed);
return wstr;
}
示例:UTF-8与wstring之间转换
立即学习“C++免费学习笔记(深入)”;
#include <locale> #include <codecvt> <p>// 创建转换对象 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;</p><p>// 多字节(UTF-8)转宽字符 std::wstring wstr = converter.from_bytes(utf8_string);</p><p>// 宽字符转多字节(UTF-8) std::string str = converter.to_bytes(wstr);
⚠ 注意:Visual Studio可能支持较好,GCC/Clang在某些环境下行为不一致,建议仅用于简单场景。
使用utf8cpp示例:
#include <utf8.h> #include <vector> <p>// UTF-8 到 wstring std::string utf8_str = "Hello 世界"; std::vector<wchar_t> buf(utf8_str.size()); auto end = utf8::utf8to32(utf8_str.begin(), utf8_str.end(), buf.begin()); buf.resize(end - buf.begin()); std::wstring wstr(buf.begin(), buf.end());</p><p>// wstring 到 UTF-8 std::string result; utf8::utf32to8(wstr.begin(), wstr.end(), std::back_inserter(result));
基本上就这些常见方法,根据项目环境选择最合适的一种即可。
以上就是c++++怎么将宽字符和多字节字符相互转换_c++字符宽多字节转换方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号