美文网首页
linux c++中string和wstring互转

linux c++中string和wstring互转

作者: 一路向后 | 来源:发表于2021-01-21 22:20 被阅读0次

    1.源码实现

    #include <iostream>
    #include <string>
    #include <cstdio>
    #include <cstdlib>
    #include <string.h>
    #include <wchar.h>
    #include <locale.h>
    
    using namespace std;
    
    int ws2s(const wstring &ws, string &r)
    {
        const wchar_t *source = ws.c_str();
        char *dest = NULL;
        int len = 0;
        int ret = 0;
    
        len = wcslen(source) + 1;
    
        if(len <= 1)
            return 0;
    
        dest = new char[len*sizeof(wchar_t)];
    
        ret = wcstombs(dest, source, len*sizeof(wchar_t));
    
        r = string(dest);
    
        delete[] dest;
    
        return ret;
    }
    
    int s2ws(const string &s, wstring &r)
    {
        const char *source = s.c_str();
        wchar_t *dest = NULL;
        int len = 0;
        int ret = 0;
    
        len = strlen(source) + 1;
    
        if(len <= 1)
            return 0;
    
        dest = new wchar_t[len];
    
        ret = mbstowcs(dest, source, len);
    
        r = wstring(dest);
    
        delete[] dest;
    
        return ret;
    }
    
    int main()
    {
        string a("你好,世界");
        wstring b;
        string c;
    
        setlocale(LC_CTYPE, "zh_CN.utf8");
    
        s2ws(a, b);
        ws2s(b, c);
    
        cout << c << endl;
    
        return 0;
    }
    

    2.编译源码

    $ g++ -o example example.cpp
    

    3.运行及其结果

    $ ./example
    你好,世界
    

    相关文章

      网友评论

          本文标题:linux c++中string和wstring互转

          本文链接:https://www.haomeiwen.com/subject/pjljzktx.html