How to convert from wchar_t to LPSTR?

前端 未结 2 1177
再見小時候
再見小時候 2021-01-02 09:33

How can I convert a string from wchar_t to LPSTR.

相关标签:
2条回答
  • 2021-01-02 09:50

    I use this

    wstring mywstr( somewstring );
    string mycstr( mywstr.begin(), mywstr.end() );
    

    then use it as 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());
    
    0 讨论(0)
  • 2021-01-02 09:53

    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();
    
    0 讨论(0)
提交回复
热议问题