怎么把wchar_t转换成LPSTR? [英] How to convert from wchar_t to LPSTR?

查看:186
本文介绍了怎么把wchar_t转换成LPSTR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I convert a string from wchar_t to LPSTR.

推荐答案

wchar_t 字符串由16位单元组成,即 LPSTR 是指向八位字节串的指针,定义如下:

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;

重要的是LPSTR 可以终止。

What's important is that the LPSTR may be null-terminated.

wchar_t 转换为 LPSTR 时,您必须决定关于要使用的编码。完成此操作后,您可以使用 WideCharToMultiByte 函数执行转换。

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.

例如,以下是翻译宽字符串转换为UTF8,使用STL字符串简化内存管理:

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] );
}

您可以使用此功能翻译 wchar_t * LPSTR

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

这篇关于怎么把wchar_t转换成LPSTR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆