我只是想获取 x11 窗口标题,并将其存储在 std::wstring 中。我使用这样的命令来获取标题
auto req_title = xcb_get_property(conn, 0, window, XCB_ATOM_WM_NAME, XCB_GET_PROPERTY_TYPE_ANY, 0, 100);
auto res_title = xcb_get_property_reply(conn, req_title, nullptr);
之后,我可以获得存储在 char 数组中的标题。如何将此数组转换为 wstring?
最佳答案
当前解决方案
您可以使用 std::wstring_convert
使用 codecvt
将 string
与 wstring
相互转换指定要执行的转换。
使用示例:
string so=u8"Jérôme Ângle";
wstring st;
wstring_convert<std::codecvt_utf8<wchar_t>,wchar_t> converter;
st = converter.from_bytes(so);
如果你有一个 c 字符串(char 数组),from_bytes()
的重载将完全按照你的意愿执行:
char p[]=u8"Jérôme Ângle";
wstring ws = converter.from_bytes(p);
是否可持续?
正如评论中指出的那样,C++17 has deprecated codecvt
和 wstring_convert
实用程序:
These features are hard to use correctly, and there are doubts whether they are even specified correctly. Users should use dedicated text-processing libraries instead.
此外,wstring
是基于 wchar_t
的,后者在 linux 系统和 windows 系统上具有非常不同的编码。
所以第一个问题是问为什么需要 wstring
,为什么不保留 utf-8 everywhere .
根据原因,您可以考虑使用:
- ICU及其
UnicodeString
获得完整、深入的 unicode 支持 - boost.locale它的
to_utf
或utf_to_utf
,用于常见的 unicode 相关任务。 - utf8-cpp用于以 unicode 方式处理 utf8 字符串(注意,似乎没有维护)。
关于c++ - UTF8 字符数组到 std::wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53177771/