Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c++ - 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++?

question from:https://stackoverflow.com/questions/65861280/convert-stdstring-to-stdwstring-and-vise-versa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...