简体   繁体   English

将 std::string 转换为 std::wstring ,反之亦然

[英]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.我已经阅读了很多关于如何在std::stringstd::wstring之间进行转换的内容,但是我找到的所有答案都非常古老。 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.我尝试使用std::codecvt进行转换,但它给出了一个警告,指出它已被弃用,并使用Windows.h header 文件使用WideCharToMultiByte()MultiByteToWideChar() 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++?有没有办法在现代C++ 中将std::string转换为std::wstring ,反之亦然?

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). std::wstring包含wchar_t元素,并且wchar_t是跨平台的不同大小(Windows 上的 2 个字节,其他地方的 4 个字节),因此std::wstring跨平台使用不同的编码(Windows 上的 UTF-16,其他地方的 UTF-32 )。 Just as std::string can hold different 8bit encodings (UTF-8, ISO-8859-x, Windows-125x, etc).就像std::string可以保存不同的 8 位编码(UTF-8、ISO-8859-x、Windows-125x 等)一样。

So, you are not asking how to convert between std::string and std::wstring themselves, but how to convert between different encodings.因此,您不是在问如何在std::stringstd::wstring本身之间进行转换,而是在问如何在不同的编码之间进行转换。 And the fact is, C++ simply doesn't support that natively.事实是,C++ 根本不支持本机。 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. C++11 试图用std::codecvtstd::wstring_convert解决这个问题,但它们是有限的,正如你所指出的,它已经在 C++17 中被弃用,没有替代品。

So, you best options is to use 3rd party cross-platform libraries, such as ICU, ICONV, etc.因此,您最好的选择是使用 3rd 方跨平台库,例如 ICU、ICONV 等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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