23

Function CommandLineToArgvW is giving me commandline arguments in LPWSTR type. I need these arguments in string. Would someone please tell me how to convert LPWSTR to string?
I'm using mingw.

default
  • 11,485
  • 9
  • 66
  • 102
leggo
  • 309
  • 2
  • 3
  • 11

4 Answers4

32
std::string MyString = CW2A (L"LPWSTR STRING");

You need to include atlstr.h for CW2A

Raxvan
  • 6,257
  • 2
  • 25
  • 46
Chris Dargis
  • 5,891
  • 4
  • 39
  • 63
9

Try to use following API functions :

  1. WideCharToMultiByte

  2. wcstombs

And comparision of both methods WideCharToMultiByte() vs. wcstombs()

Community
  • 1
  • 1
rkosegi
  • 14,165
  • 5
  • 50
  • 83
1

Let's say yout LPWSTR variable is myVarL:

wstring ws( myVarL ); 
string myVarS = string( ws.begin(), ws.end() );

should make what you want

  • 3
    This will not properly deal with most of the possible characters in a wide string – M.M Nov 22 '18 at 06:04
0

This is how you can convert LPWSTR to string:

// Assume you have initialized the lpwstr variable
std::wstring wString;
wString.append(&lpwstr[0]);
std::string convertedString(wString.begin(), wString.end());

Easy peasy

  • 1
    Please explain how this answer is any better than the one by Lambert Duran several years ago. And also explain how this "conversion" deals with characters outside the basic ASCII set. – TheUndeadFish Jul 30 '22 at 17:37
  • Lambert's solution was easy. This one is easy peasy. Duh. – M Katz Nov 14 '22 at 04:57