in C++ by (12.3k points)
0 like 0 dislike

How I can std::string convert/translate to std::wstring in C++?

cpp string to wstring

1 Answer

0 like 0 dislike
by (12.3k points)

There are many ways. Here are a couple:

Way one

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string str = converter.to_bytes(L"Hello world");
std::wstring wstr = converter.from_bytes("Hello world");

Way two

Only works for single byte characters:

std::string str("Hello world!");
std::wstring wstr(str.begin(), str.end());

In C++17, <codecvt> header became deprecated, like std::wstring_convert and std::wbuffer_convert template classes, so at moment there is no way to do this in general case without using third-party libraries or outdated functionality.

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.