Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

How can I convert std::wstring to const *char in C++?

like image 397
subs Avatar asked Dec 08 '10 12:12

subs


People also ask

How to convert std:: string into const char*?

You can use the c_str() method of the string class to get a const char* with the string contents.

How do you convert Wstring to Lpcwstr?

This LPCWSTR is Microsoft defined. So to use them we have to include Windows. h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.


1 Answers

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;
like image 199
icecrime Avatar answered Sep 22 '22 20:09

icecrime