从C++11开始,可以使用std::codecvt_utf8_utf16
将UTF8转换为UTF16 wchar_t
(至少在Windows上,其中wchar_t
宽度为16位):
std::wstring utf8ToWide( const char* utf8 )
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes( utf8 );
}
很遗憾在 C++17 中,
std::codecvt_utf8_utf16
被废弃了。但是有一个std::filesystem::path
具有所有可能的转换功能,例如,它具有成员函数。std::string string() const;
std::wstring wstring() const;
std::u8string u8string() const;
std::u16string u16string() const;
std::u32string u32string() const;
因此,上述函数可以重写如下:
std::wstring utf8ToWide( const char* utf8 )
{
return std::filesystem::path( (const char8_t*) utf8 ).wstring();
}
与 std::codecvt_utf8_utf16
不同,此编码转换器不会使用任何已弃用的 C++ 代码。
这样的转换器可能会有什么缺点?例如,路径长度不能超过某个长度或某些 Unicode 符号在其中被禁止使用吗?
path
实现是做什么的。或者继续使用codecvt_utf8_utf16
。 - Panagiotis Kanavosstd::filesystem::path
进行额外复制,或者使用MultiByteToWideChar
。不管怎样,OP似乎在使用Windows。 - Ayxan Haqverdili