简体   繁体   中英

Convert std::string to std::wstring and vise versa

I've been reading quite a lot about how to convert between std::string and std::wstring but all the answers I have found was very old. I tried using std::codecvt to convert but it gives a warning stating that it is deprecated and use WideCharToMultiByte() and MultiByteToWideChar() using the Windows.h header file. But then, I'm not sure if I can make it work on other platforms.

Is there a way to convert std::string to std::wstring and vise versa in modern C++?

std::wstring holds wchar_t elements, and wchar_t is a different size across platforms (2 bytes on Windows, 4 bytes elsewhere), and as such std::wstring uses different encodings across platforms (UTF-16 on Windows, UTF-32 elsewhere). Just as std::string can hold different 8bit encodings (UTF-8, ISO-8859-x, Windows-125x, etc).

So, you are not asking how to convert between std::string and std::wstring themselves, but how to convert between different encodings. And the fact is, C++ simply doesn't support that natively. C++11 tried to address that with std::codecvt and std::wstring_convert , but they are limited, and as you have noted have since been deprecated in C++17, with no replacement is sight.

So, you best options is to use 3rd party cross-platform libraries, such as ICU, ICONV, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM