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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:44:23  来源:igfitidea点击:

How to convert from wchar_t to LPSTR?

c++visual-c++

提问by nidhal

How can I convert a string from wchar_tto LPSTR.

我怎么能转换为字符串,从wchar_tLPSTR

采纳答案by Frerich Raabe

A wchar_tstring is made of 16-bit units, a LPSTRis 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_tto LPSTR, you have to decide on an encoding to use. Once you did that, you can use the WideCharToMultiBytefunction 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 LPSTRlike 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());