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;
复制代码

 

posted on   空明流光  阅读(296)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2016-09-02 C# 更新SQL Server数据库备注信息从另一数据库

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示