How to convert wstring into string?

前端 未结 17 2264
北海茫月
北海茫月 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:21

    Besides just converting the types, you should also be conscious about the string's actual format.

    When compiling for Multi-byte Character set Visual Studio and the Win API assumes UTF8 (Actually windows encoding which is Windows-28591 ).
    When compiling for Unicode Character set Visual studio and the Win API assumes UTF16.

    So, you must convert the string from UTF16 to UTF8 format as well, and not just convert to std::string.
    This will become necessary when working with multi-character formats like some non-latin languages.

    The idea is to decide that std::wstring always represents UTF16.
    And std::string always represents UTF8.

    This isn't enforced by the compiler, it's more of a good policy to have. Note the string prefixes I use to define UTF16 (L) and UTF8 (u8).

    To convert between the 2 types, you should use: std::codecvt_utf8_utf16< wchar_t>

    #include 
    
    #include 
    
    int main()
    {
    
        std::string original8 = u8"הלו";
    
        std::wstring original16 = L"הלו";
    
        //C++11 format converter
        std::wstring_convert> convert;
    
        //convert to UTF8 and std::string
        std::string utf8NativeString = convert.to_bytes(original16);
    
        std::wstring utf16NativeString = convert.from_bytes(original8);
    
        assert(utf8NativeString == original8);
        assert(utf16NativeString == original16);
    
        return 0;
    }
    

提交回复
热议问题