1. 程式人生 > 其它 >C++ wstring和string想互轉換

C++ wstring和string想互轉換

不支援中文

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