c++ string to wstring

Converting C++ string to wstring

#include <iostream>
#include <string>
#include <locale>
using namespace std;

int main() {
    string narrowString = "Hello, world!";
    wstring wideString;

    // Create a locale object with the default locale
    locale loc;

    // Use the std::wstring_convert to convert the narrow string to wide string
    wstring_convert<codecvt_utf8<wchar_t>> converter;
    wideString = converter.from_bytes(narrowString);

    wcout.imbue(loc);  // Set the wide character locale to the console
    wcout << wideString << endl;

    return 0;
}
  1. Include necessary libraries:
  2. <iostream> for input/output operations
  3. <string> for string handling
  4. <locale> for localization support

  5. Define the main function.

  6. Declare a narrow string narrowString and a wide string wideString.

  7. Create a locale object loc with the default locale.

  8. Use std::wstring_convert to convert the narrow string to wide string:

  9. Create a wstring_convert object converter with the template parameter codecvt_utf8<wchar_t>.
  10. Use the from_bytes method of the converter to convert the narrowString to wideString.

  11. Set the wide character locale to the console using wcout.imbue(loc).

  12. Output the wide string to the console using wcout.

  13. Return 0 to indicate successful execution.

This code snippet demonstrates the process of converting a C++ string to a wstring.