分享

C++宽窄字符转换代码

 MikeDoc 2010-12-28
#include <iostream>
#include <string>

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<<wstr<<endl;
    cout<<"str : "<<str.size()<<endl;
    cout<<"wstr : "<<wstr.size()<<endl;

    string str2;
    str2=ws2s(wstr);
   
    return 0;
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多