How do I convert wchar_t* to std::string?

codefrog picture codefrog · Dec 2, 2010 · Viewed 59.7k times · Source

I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?

I tried this:

std::string test = args.OptionArg();

but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'

Answer

Ulterior picture Ulterior · Jul 8, 2011
std::wstring ws( args.OptionArg() );
std::string test( ws.begin(), ws.end() );