Conversion of wchar_t* to string
111,220
Solution 1
Use wstring, see this code:
// Your wchar_t*
wchar_t* txt = L"Hello World";
wstring ws(txt);
// your new String
string str(ws.begin(), ws.end());
// Show String
cout << str << endl;
Solution 2
You should use the wstring class belonging to the namespace std. It has a constructor which accepts a parameter of the type wchar_t*.
Here is a full example of using this class.
wchar_t* characters=L"Test";
std::wstring string(characters);
You do not have to use a constructor containing String.begin() and String.end() because the constructor of std::wstring automatically allocates memory for storing the array of wchar_t and copies the array to the allocated memory.
Author by
AnasShoaib90
I m learning computer science to solve world's problems.
Updated on June 07, 2020Comments
-
AnasShoaib90 almost 4 years
How can I convert an
wchar_t*
array to anstd::string
varStr in win32 console.