How to convert wstring into string?

前端 未结 17 2168
北海茫月
北海茫月 2020-11-22 13:10

The question is how to convert wstring to string?

I have next example :

#include 
#include 

int main()
{
    std::wstr         


        
17条回答
  •  旧时难觅i
    2020-11-22 13:29

    This solution is inspired in dk123's solution, but uses a locale dependent codecvt facet. The result is in locale encoded string instead of UTF-8 (if it is not set as locale):

    std::string w2s(const std::wstring &var)
    {
       static std::locale loc("");
       auto &facet = std::use_facet>(loc);
       return std::wstring_convert::type, wchar_t>(&facet).to_bytes(var);
    }
    
    std::wstring s2w(const std::string &var)
    {
       static std::locale loc("");
       auto &facet = std::use_facet>(loc);
       return std::wstring_convert::type, wchar_t>(&facet).from_bytes(var);
    }
    

    I was searching for it, but I can't find it. Finally I found that I can get the right facet from std::locale using the std::use_facet() function with the right typename. Hope this helps.

提交回复
热议问题