杰士邦和杜蕾斯哪个薄:C++宽窄字符转换代码

来源:百度文库 编辑:中财网 时间:2024/04/28 18:21:58
#include
#include

using namespace std;

const std::wstring s2ws(const std::string s)
{
    std::locale old_loc =
        std::locale::global(std::locale(""));

    const char* src_str = s.c_str();
    const size_t buffer_size = s.size() + 1;
    wchar_t* dst_wstr = new wchar_t[buffer_size];
    wmemset(dst_wstr, 0, buffer_size);
    mbstowcs(dst_wstr, src_str, buffer_size);
    std::wstring result = dst_wstr;
    delete []dst_wstr;

    std::locale::global(old_loc);

    return result;
}

const std::string ws2s(const std::wstring ws)
{
    std::locale old_loc =
        std::locale::global(std::locale(""));

    const wchar_t* src_wstr = ws.c_str();
    size_t buffer_size = ws.size() * 4 + 1;
    char* dst_str = new char[buffer_size];
    memset(dst_str, 0, buffer_size);
    wcstombs(dst_str ,src_wstr, buffer_size);
    std::string result = dst_str;
    delete []dst_str;

    std::locale::global(old_loc);

    return result;
}

int main()
{
    wstring wstr;
    string str;
    cin>>str;
    wstr=s2ws(str);
    wcout<    cout<<"str : "<    cout<<"wstr : "<
    string str2;
    str2=ws2s(wstr);
   
    return 0;
}