簡體   English   中英

如何轉換wchar_t至LPSTR?

[英]How to convert from wchar_t to LPSTR?

如何將字符串從wchar_t轉換為LPSTR

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

我用這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM