How to convert from wchar_t to LPSTR

How to convert a string from wchar_t to LPSTR. thanks for the answer.

+4
source share
2 answers
Line

A wchar_t consists of 16-bit units, and LPSTR is a pointer to an octet string, defined as follows:

 typedef char* PSTR, *LPSTR; 

The important thing is that LPSTR can be completed with a zero mark.

When translating from wchar_t to LPSTR you need to determine the encoding used. After that, you can use the WideCharToMultiByte function to perform the conversion.

For example, here's how to translate a widescreen string to 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 can use this function to translate wchar_t* to LPSTR as follows:

 const wchar_t *str = L"Hello, World!"; std::string utf8String = utf16ToUTF8( str ); LPSTR lpStr = utf8String.c_str(); 
+7
source

I use this

 wstring mywstr( somewstring ); string mycstr( mywstr.begin(), mywstr.end() ); 

then use it as mycstr.c_str ()

(edit, as I cannot comment), here 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()); 
0
source

Source: https://habr.com/ru/post/1386680/


All Articles