convert std::wstring to const *char in c++

You can convert a std::wstring to a const wchar_t * using the c_str member function :

std::wstring wStr;
const wchar_t *str = wStr.c_str();

However, a conversion to a const char * isn't natural : it requires an additional call to std::wcstombs, like for example:

#include <cstdlib>

// ...

std::wstring wStr;
const wchar_t *input = wStr.c_str();

// Count required buffer size (plus one for null-terminator).
size_t size = (wcslen(input) + 1) * sizeof(wchar_t);
char *buffer = new char[size];

#ifdef __STDC_LIB_EXT1__
    // wcstombs_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined
    size_t convertedSize;
    std::wcstombs_s(&convertedSize, buffer, size, input, size);
#else
    std::wcstombs(buffer, input, size);
#endif

/* Use the string stored in "buffer" variable */

// Free allocated memory:
delete buffer;

You cannot do this just like that. std::wstring represents a string of wide (Unicode) characters, while char* in this case is a string of ASCII characters. There has to be a code page conversion from Unicode to ASCII.

To make the conversion you can use standard library functions such as wcstombs, or Windows' WideCharToMultiByte function.

Updated to incorporate information from comments, thanks for pointing that out.

Tags:

C++