如何将字符串从wchar_t
转换为LPSTR
。
答案 0 :(得分:8)
wchar_t
字符串由16位单元组成,LPSTR
是指向八位字节字符串的指针,定义如下:
typedef char* PSTR, *LPSTR;
重要的是LPSTR 可以以空值终止。
从wchar_t
转换为LPSTR
时,您必须决定要使用的编码。完成后,您可以使用WideCharToMultiByte
函数执行转换。
例如,以下是如何将宽字符串转换为UTF8,使用STL字符串来简化内存管理:
#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] );
}
您可以使用此功能将wchar_t*
翻译为LPSTR
,如下所示:
const wchar_t *str = L"Hello, World!";
std::string utf8String = utf16ToUTF8( str );
LPSTR lpStr = utf8String.c_str();
答案 1 :(得分:1)
我用这个
wstring mywstr( somewstring );
string mycstr( mywstr.begin(), mywstr.end() );
然后将其用作mycstr.c_str()
(编辑,因为我无法评论)这就是我使用它的方式,它运行正常:
#include <string>
std::wstring mywstr(ffd.cFileName);
std::string mycstr(mywstr.begin(), mywstr.end());
pRequest->Write(mycstr.c_str());