不支持中文

std::wstring wide = L"wide";
std::string str(wide.begin(), wide.end());

std::string s = "hello";
std::wstring ws(s.begin(), s.end());

支持中文

#include <comdef.h>
#include <string>


std::string wstring2string(std::wstring wstr)
{
    // support chinese
    std::string res;
    int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), nullptr, 0, nullptr, nullptr);
    if (len <= 0){
        return res;
    }
    char* buffer = new char[len + 1];
    if (buffer == nullptr){
        return res;
    }
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, nullptr, nullptr);
    buffer[len] = '\0';
    res.append(buffer);
    delete[] buffer;
    return res;
}


std::wstring string2wstring(std::string wstr)
{
    std::wstring res;
    int len = MultiByteToWideChar(CP_ACP, 0, wstr.c_str(), wstr.size(), nullptr, 0);
    if( len < 0 ){
        return res;
    }
    wchar_t* buffer = new wchar_t[len + 1];
    if( buffer == nullptr){
        return res;
    }
    MultiByteToWideChar(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len);
    buffer[len] = '\0';
    res.append(buffer);
    delete[] buffer;
    return res;
}

参考链接

https://stackoverflow.com/questions/4804298/how-to-convert-wstring-into-string

相关文章:

  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
  • 2021-12-23
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
  • 2021-05-22
猜你喜欢
  • 2022-12-23
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2023-03-18
  • 2021-09-18
相关资源
相似解决方案