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;
}
- Include necessary libraries:
<iostream>
for input/output operations<string>
for string handling<locale>
for localization supportDefine the main function.
Declare a narrow string
narrowString
and a wide stringwideString
.Create a locale object
loc
with the default locale.Use
std::wstring_convert
to convert the narrow string to wide string:- Create a
wstring_convert
objectconverter
with the template parametercodecvt_utf8<wchar_t>
. Use the
from_bytes
method of the converter to convert thenarrowString
towideString
.Set the wide character locale to the console using
wcout.imbue(loc)
.Output the wide string to the console using
wcout
.Return 0 to indicate successful execution.
This code snippet demonstrates the process of converting a C++ string to a wstring.