How to convert string to wstring in C++

前端 未结 1 1303
灰色年华
灰色年华 2020-12-06 14:39

I have programmed some code but there is some problem. In this codes i am trying to convert string to wstring. But this string have \"█\" characters. This character have 219

1条回答
  •  渐次进展
    2020-12-06 15:17

    The C-library solution for converting between the system's narrow and wide encoding use the mbsrtowcs and wcsrtombs functions from the header. I've spelt this out in this answer.

    In C++11, you can use the wstring_convert template instantiated with a suitable codecvt facet. Unfortunately this requires some custom rigging, which is spelt out on the cppreference page.

    I've adapted it here into a self-contained example which converts a wstring to a string, converting from the system's wide into the system's narrow encoding:

    #include 
    #include 
    #include 
    #include 
    
    // utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
    template 
    struct deletable_facet : Facet
    {
        using Facet::Facet;
    };
    
    int main()
    {
        std::wstring_convert<
            deletable_facet>> conv;
    
        std::wstring ws(L"Hello world.");
        std::string ns = conv.to_bytes(ws);
    
        std::cout << ns << std::endl;
    }
    

    0 讨论(0)
提交回复
热议问题