C++ 如何从 wchar_t 转换为 LPSTR?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8532855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert from wchar_t to LPSTR?
提问by nidhal
How can I convert a string from wchar_t
to LPSTR
.
我怎么能转换为字符串,从wchar_t
到LPSTR
。
采纳答案by Frerich Raabe
A wchar_t
string is made of 16-bit units, a LPSTR
is a pointer to a string of octets, defined like this:
一个wchar_t
字符串由 16 位单元组成,aLPSTR
是一个指向八位字节串的指针,定义如下:
typedef char* PSTR, *LPSTR;
What's important is that the LPSTR maybe null-terminated.
重要的是 LPSTR可以以空值结尾。
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.
当从 转换wchar_t
为 时LPSTR
,您必须决定要使用的编码。完成此操作后,您可以使用该WideCharToMultiByte
函数执行转换。
For instance, here's how to translate a wide-character string into UTF8, using STL strings to simplify memory management:
例如,这里是如何将宽字符串转换为 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] );
}
You could use this function to translate a wchar_t*
to LPSTR
like this:
您可以使用此函数将 a 翻译wchar_t*
成LPSTR
这样:
const wchar_t *str = L"Hello, World!";
std::string utf8String = utf16ToUTF8( str );
LPSTR lpStr = utf8String.c_str();
回答by Ulterior
I use this
我用这个
wstring mywstr( somewstring );
string mycstr( mywstr.begin(), mywstr.end() );
then use it as mycstr.c_str()
然后将其用作 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());