电竞比分网-中国电竞赛事及体育赛事平台

分享

C++寬窄字符轉(zhuǎn)換代碼

 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;
}


    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多