How to convert wstring into string?

前端 未结 17 2262
北海茫月
北海茫月 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条回答
  •  臣服心动
    2020-11-22 13:19

    As Cubbi pointed out in one of the comments, std::wstring_convert (C++11) provides a neat simple solution (you need to #include and ):

    std::wstring string_to_convert;
    
    //setup converter
    using convert_type = std::codecvt_utf8;
    std::wstring_convert converter;
    
    //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
    std::string converted_str = converter.to_bytes( string_to_convert );
    

    I was using a combination of wcstombs and tedious allocation/deallocation of memory before I came across this.

    http://en.cppreference.com/w/cpp/locale/wstring_convert

    update(2013.11.28)

    One liners can be stated as so (Thank you Guss for your comment):

    std::wstring str = std::wstring_convert>().from_bytes("some string");
    

    Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)

    std::wstring s2ws(const std::string& str)
    {
        using convert_typeX = std::codecvt_utf8;
        std::wstring_convert converterX;
    
        return converterX.from_bytes(str);
    }
    
    std::string ws2s(const std::wstring& wstr)
    {
        using convert_typeX = std::codecvt_utf8;
        std::wstring_convert converterX;
    
        return converterX.to_bytes(wstr);
    }
    

    Note: there's some controversy on whether string/wstring should be passed in to functions as references or as literals (due to C++11 and compiler updates). I'll leave the decision to the person implementing, but it's worth knowing.

    Note: I'm using std::codecvt_utf8 in the above code, but if you're not using UTF-8 you'll need to change that to the appropriate encoding you're using:

    http://en.cppreference.com/w/cpp/header/codecvt

提交回复
热议问题