【问题标题】:How to convert from wchar_t to LPSTR?如何从 wchar_t 转换为 LPSTR?
【发布时间】:2011-12-16 10:29:37
【问题描述】:

如何将字符串从wchar_t 转换为LPSTR

【问题讨论】:

  • 你的意思是从LPWSTRLPSTR

标签: c++ visual-c++


【解决方案1】:

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();

【讨论】:

  • 应该注意的是,16 位是特定于 windows 的,其他实现可能(并且将会)具有不同的 wchar_t 和/或 char 大小。
  • 谢谢,要将 LPSTR 转换为 wstring,我该怎么做?
  • @PlasmaHH:是的,这是真的 - 我严格来说是在考虑 Windows(因为它被标记为 visual-c++)。
  • @nidahl:为此,您可以使用MultiByteToWideChar 函数。
  • @Frerich:我只是用 MultiByteToWideChar 替换 WideCharToMultiByte?
【解决方案2】:

我用这个

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());

【讨论】:

  • 那些功能是什么?
猜你喜欢
  • 2017-02-03
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2018-01-07
  • 2011-03-14
  • 2017-04-07
相关资源
最近更新 更多