c++ string 与 wstring 互转并解决显示乱码
string 转 wstring:
#include <iostream>
#include <sstream>
#include <locale>
#include <string>
#include <codecvt>
int main() {
std::string utf8_str = "你好,世界!";
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::wstring wide_str = converter.from_bytes(utf8_str);
std::wcout.imbue(std::locale("zh_CN"));
std::wcout << wide_str << std::endl;
return 0;
}
wstring 转 string:
#include <iostream> #include <sstream> #include <locale> #include <string> #include <codecvt> int main() { system("chcp 65001"); std::wstring wide_str = L"你好,世界!"; std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; std::string utf8_str = converter.to_bytes(wide_str); std::cout.imbue(std::locale("chs")); // std::cout.imbue(std::locale("zh_CN")) 兼容性可能更好,但未测试 std::cout << utf8_str << std::endl; return 0; }
编码 65001(UTF-8) 下 cout 和 wcout 不乱码:
// 设置控制台为 UTF-8 编码 system("chcp 65001"); // 设置 wcout 的 locale 为 UTF-8 std::wcout.imbue(std::locale(std::locale(), new std::codecvt_utf8<wchar_t>())); // 输出宽字符字符串 std::wcout << L"你好,世界!" << std::endl; std::cout << "你好,世界!" << endl;
编码 936(GBK) 下 cout 和 wcout 不乱码(windows 控制台默认使用GBK):
#include <windows.h>
std::string utf8_to_gbk(const std::string& utf8_str) {
// Convert UTF-8 to wide string
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, nullptr, 0);
std::wstring wstr(wlen, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, &wstr[0], wlen);
// Convert wide string to GBK
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string gbk_str(len, 0);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &gbk_str[0], len, nullptr, nullptr);
return gbk_str;
}
//示例
system("chcp 936");
std::wcout.imbue(std::locale("zh_CN"));
std::wcout << L"你好,世界!" << std::endl;
// 输出 GBK 编码字符串
std::cout << utf8_to_gbk("你好,世界!") << std::endl;
桂棹兮兰桨,击空明兮溯流光。