Convert WCHAR[260] to std::string

user1334943 picture user1334943 · Apr 18, 2012 · Viewed 17.2k times · Source

I have gotten a WCHAR[MAX_PATH] from (PROCESSENTRY32) pe32.szExeFile on Windows. The following do not work:

std::string s;
s = pe32.szExeFile; // compile error. cast (const char*) doesnt work either

and

std::string s;
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
s = pe32.szExeFile;

Answer

EdChum picture EdChum · Apr 18, 2012

For your first example you can just do:

std::wstring s(pe32.szExeFile);

and for second:

char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
std::wstring s(pe32.szExeFile);

as std::wstring has a char* ctor