36

How can I convert an wchar_t* array to an std::string varStr in win32 console.

kvantour
  • 25,269
  • 4
  • 47
  • 72
AnasShoaib90
  • 629
  • 2
  • 7
  • 14

2 Answers2

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
  • 45
    Completelly 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
  • 2
    WARNING: 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
  • The compiler will also warn about possible loss of data here. – qz- Jul 02 '23 at 03:51
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