如何从wchar_t转换为LPSTR [英] How to convert from wchar_t to LPSTR
问题描述
如何将一个字符串从wchar_t转换为LPSTR。
感谢回答。
wchar_t
由16位单元构成, LPSTR
是指向八位字节字符串的指针,定义如下:
typedef char * PSTR,* LPSTR;
重要的是LPSTR 可以 p>
从 wchar_t
翻译为 LPSTR
时,对使用的编码。完成后,您可以使用 WideCharToMultiByte
函数来执行转换。
例如,以下是如何将宽字符串转换为UTF8 ,使用STL字符串简化内存管理:
#include< windows.h>
#include< string>
#include< vector>
静态字符串utf16ToUTF8(const wstring& s)
{
const int size = :: WideCharToMultiByte(CP_UTF8,0,s.c_str(),-1, 0,0,NULL);
矢量< 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 = LHello,World!;
std :: string utf8String = utf16ToUTF8(str);
LPSTR lpStr = utf8String.c_str();
How can i convert a string from wchar_t to LPSTR. thanks for answer.
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();
这篇关于如何从wchar_t转换为LPSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!