How can I convert a string from wchar_t
to LPSTR
.
A wchar_t
string is made of 16-bit units, a LPSTR
is a pointer to a string of octets, defined like this:
typedef char* PSTR, *LPSTR;
What's important is that the LPSTR may be null-terminated.
When translating from wchar_t
to LPSTR
, you have to decide on an encoding to use. Once you did that, you can use the WideCharToMultiByte
function to perform the conversion.
For instance, here's how to translate a wide-character string into UTF8, using STL strings to simplify memory management:
#include <windows.h>
#include <string>
#include <vector>
static string utf16ToUTF8( const wstring &s )
{
const int size = ::WideCharToMultiByte( CP_UTF8, 0, s.c_str(), -1, NULL, 0, 0, NULL );
vector<char> buf( size );
::WideCharToMultiByte( CP_UTF8, 0, s.c_str(), -1, &buf[0], size, 0, NULL );
return string( &buf[0] );
}
You could use this function to translate a wchar_t*
to LPSTR
like this:
const wchar_t *str = L"Hello, World!";
std::string utf8String = utf16ToUTF8( str );
LPSTR lpStr = utf8String.c_str();
I use this
wstring mywstr( somewstring );
string mycstr( mywstr.begin(), mywstr.end() );
then use it as mycstr.c_str()
(edit, since i cannot comment) this is how i used this, and it works fine:
#include <string>
std::wstring mywstr(ffd.cFileName);
std::string mycstr(mywstr.begin(), mywstr.end());
pRequest->Write(mycstr.c_str());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With