小

小南瓜

技术问题总结

  • 首页
Home c++中string和wstring相互转换
文章

c++中string和wstring相互转换

Posted 2024-02-25 Updated 2024-02- 25
By 小南瓜
3~4 min read

string转wstring代码

wstring StringToWString(const string &str)
{
    int num = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
    wchar_t *wide = new wchar_t[num];
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, num);
    wstring w_str(wide);
    delete[] wide;
    return w_str;
}

wstring转string代码

string WStringToString(const wstring &wstr)
{
    string str;
    int nLen = (int)wstr.length();
    str.resize(nLen, ' ');
    int nResult = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wstr.c_str(), nLen, (LPSTR)str.c_str(), nLen, NULL, NULL);
    if (nResult == 0)
    {
        return "";
    }
    return str;
}

utf8编码特殊处理

如果程序中有使用中文,并且编码为utf-8的话,可能会出现乱码,可以尝试使用下面的方法:

wstring StringToWString(const string& str)
{
    setlocale(LC_ALL, "zh_CN");
    const char* point_to_source = str.c_str();
    size_t new_size = str.size() + 1;
    wchar_t *point_to_destination = new wchar_t[new_size];
    wmemset(point_to_destination, 0, new_size);
    mbstowcs(point_to_destination, point_to_source, new_size);
    wstring result = point_to_destination;
    delete[]point_to_destination;
    return result;
}

编程开发
C++
License:  CC BY 4.0
Share

Further Reading

Nov 29, 2024

Java使用oshi-core获取服务器、CPU、JVM、内存、磁盘等信息

最近在弄后台管理系统,但由于功能不太多,准备弄个系统信息的界面来丰富下,经过查询,发现java中有oshi库可以很方便的获取系统信息。 oshi是什么 oshi是一个基于Java的开源库,它能够跨平台地获取操作系统、硬件和系统资源的信息。它利用底层操作系统的API,以统一的接口形式为Java应用程序

Nov 14, 2024

Java PKIX SSL证书校验错误及解决方案

服务器上程序发起https请求时,有些时候会遇到下面的错误: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderExcept

Feb 25, 2024

c++中string和wstring相互转换

string转wstring代码 wstring StringToWString(const string &str) { int num = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); wchar_t

OLDER

c++实现gbk、utf8编码转换

NEWER

前端项目运行、打包是提示ERR_OSSL_EVP_UNSUPPORTED错误

Recently Updated

  • Java使用oshi-core获取服务器、CPU、JVM、内存、磁盘等信息
  • 基于vue3、antvue、cropperjs轻松实现图片完美裁剪,打造个性化上传体验
  • Java PKIX SSL证书校验错误及解决方案
  • Centos升级openssl
  • 前端项目运行、打包是提示ERR_OSSL_EVP_UNSUPPORTED错误

Trending Tags

Halo C++ vite centos openssl java springboot vue 前端

Contents

©2025 小南瓜. Some rights reserved. 粤ICP备20020668号-1

Using the Halo theme Chirpy