Conversion to std::wstring

suggest change

In C++, sequences of characters are represented by specializing the std::basic_string class with a native character type. The two major collections defined by the standard library are std::string and std::wstring:

The conversion depends on the encodings represented by each string type; there is no general character-by-character conversion between std::string and std::wstring. The following legacy example assumes UTF-8 for the narrow string. codecvt_utf8<wchar_t> converts each wchar_t as one code point, so it does not reassemble UTF-16 surrogate pairs:

std::wstring_convert and the <codecvt> conversion facets were deprecated in C++17 and removed in C++26. For new code, use a maintained Unicode library or a platform conversion API with explicit source and destination encodings.

#include <string>
#include <codecvt>
#include <locale>

std::string input_str = "this is a -string-, which is a sequence based on the -char- type.";
std::wstring input_wstr = L"this is a -wide- string, which is based on the -wchar_t- type.";

// conversion
std::wstring str_turned_to_wstr = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(input_str);

std::string wstr_turned_to_str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(input_wstr);

In order to improve usability and/or readability, you can define functions to perform the conversion:

#include <string>
#include <codecvt>
#include <locale>

using convert_t = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_t, wchar_t> strconverter;

std::string to_string(std::wstring wstr)
{
    return strconverter.to_bytes(wstr);
}

std::wstring to_wstring(std::string str)
{
    return strconverter.from_bytes(str);
}

Sample usage:

std::wstring a_wide_string = to_wstring("Hello World!");

That’s certainly more readable than std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("Hello World!").

Neither char nor wchar_t specifies an encoding. On Windows, wchar_t is commonly 16 bits and strings generally use UTF-16; on many Unix-like systems it is commonly 32 bits. char16_t and char32_t are intended for UTF-16 and UTF-32 code units, respectively. A UTF-16 code unit is not necessarily a complete Unicode code point because supplementary characters use surrogate pairs.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents