How can I convert an wchar_t*
array to an std::string
varStr in win32 console.
Asked
Active
Viewed 1.4e+01k times
36

kvantour
- 25,269
- 4
- 47
- 72

AnasShoaib90
- 629
- 2
- 7
- 14
-
http://stackoverflow.com/questions/4339960/how-do-i-convert-wchar-t-to-stdstring – RC Brand Dec 31 '14 at 11:36
-
show your code, please (the Win32 API) functions – grisha Dec 31 '14 at 12:01
2 Answers
59
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;

FelipeDurar
- 1,163
- 9
- 15
-
45Completelly wrong. This fails if `txt` contains any non–ascii character. If you replace `"Hello World"` with `"…"`, then `…` becomes `&`. This *solution* is highly harmful, causing data loss. – Jan 29 '18 at 23:15
-
2WARNING: Use this ONLY if the source string is made of ASCII characters. As previous comment says, extended (multi-byte) Unicode characters may be lost or replaced by garbage. – Simón Apr 03 '20 at 14:13
-
10
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.

Norbert Willhelm
- 2,579
- 1
- 23
- 33