1

I just trying to get x11 window title, and store it in std::wstring. I use such command to get the title

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);

After that, I can get title stored in char array. How can I convert this array to wstring?

2

1 Answer 1

1

Current solution

You can use std::wstring_convert to convert a string to or from wstring, using a codecvt to specify the conversion to be performed.

Example of use:

string so=u8"Jérôme Ângle"; 
wstring st; 
wstring_convert<std::codecvt_utf8<wchar_t>,wchar_t> converter;
st = converter.from_bytes(so);

If you have a c-string (array of char), the overloads of from_bytes() will do exactly what you want:

char p[]=u8"Jérôme Ângle";
wstring ws = converter.from_bytes(p);

Online demo

Is it sustainable ?

As pointed out in the comments, C++17 has deprecated codecvt and the wstring_convert utility:

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.

In addition, a wstring is based on wchar_t which has a very different encoding on linux systems and on windows systems.

So the first question would be to ask why a wstring is needed at all, and why not just keep utf-8 everywhere.

Depending on the reasons, you may consider to use:

  • ICU and its UnicodeString for a full, in-depth, unicode support
  • boost.locale an its to_utf or utf_to_utf, for common unicode related tasks.
  • utf8-cpp for working with utf8 strings the unicode way (attention, seems not maintained).
Sign up to request clarification or add additional context in comments.

8 Comments

Note wstring_convert and wbuffer_convert and codecvt_utf8 are all deprecated in C++17.
from_bytes() has overloads that accept a null-terminated char* string, and two char* iterators denoting a range, so you don't need to wrap your char data in a temporary std::string if it didn't start life that way to begin with.
@Christophe IMO just wrap the std::wstring_convert code in neat little functions (eg. utf8_to_ws(...) & ws_to_utf8(...)) Then you don't spread its use throughout the applications. Then when it is changed you only have to change one function, not all your code.
@RemyLebeau thanks for pointing this out! I've edited accordingly.
@Galik wise idea ! Especially when I read "Users should use dedicated text-processing libraries instead." in a working paper of the standard committee
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.