std string to wstring

To convert a std::string to a std::wstring in C++, you can follow these steps:

  1. Include the necessary headers:
#include <string> // for std::string and std::wstring
#include <locale> // for std::wstring_convert
#include <codecvt> // for std::codecvt_utf8_utf16
  1. Declare a std::wstring variable to hold the converted wide string:
std::wstring wideStr;
  1. Create a std::wstring_convert object with the std::codecvt_utf8_utf16 converter:
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  1. Use the converter to convert the std::string to a std::wstring:
wideStr = converter.from_bytes(str);

where str is the std::string you want to convert.

Here's an example that puts it all together:

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

std::wstring stringToWstring(const std::string& str) {
    std::wstring wideStr;
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    wideStr = converter.from_bytes(str);
    return wideStr;
}

int main() {
    std::string str = "Hello, world!";
    std::wstring wideStr = stringToWstring(str);
    // Use the wide string as needed
    return 0;
}

In this example, the stringToWstring function takes a std::string as input and returns a std::wstring. You can use this function to convert any std::string to a std::wstring in your code.

Remember to include the necessary headers and use the appropriate character encoding, in this case, std::codecvt_utf8_utf16 for converting between UTF-8 and UTF-16 encodings.