wstring_convert

char*和wchar_t*之间的相互转换。

W2A及A2W

要点:
- USES_CONVERSION;
- W2A及A2W
- 只能用在c++代码中。

代码:
#include

wstring_convert

参考: http://www.cplusplus.com/reference/locale/wstring_convert/

最新的C++编译器才行。

该链接中的代码示例:

// converting from UTF-32 to UTF-8
#include <iostream>       // std::cout, std::hex
#include <string>         // std::string, std::u32string
#include <locale>         // std::wstring_convert
#include <codecvt>        // std::codecvt_utf8
#include <cstdint>        // std::uint_least32_t

int main ()
{
  std::u32string str32 ( U"\U00004f60\U0000597d" );  // ni hao (你好)
  std::string str8;

  std::wstring_convert<std::codecvt_utf8<char32_t>,char32_t> cv;

  str8 = cv.to_bytes(str32);

  // print contents (as their hex representations):
  std::cout << std::hex;

  std::cout << "UTF-32: ";
  for (char32_t c : str32)
    std::cout << '[' << std::uint_least32_t(c) << ']';
  std::cout << '\n';

  std::cout << "UTF-8 : ";
  for (char c : str8)
    std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';
  std::cout << '\n';

  return 0;
}

WideCharToMultiByte()

示例转换函数:

bool ws2s(const std::wstring& ws, std::string& s)
{
    const wchar_t* pws = ws.c_str();
    int iByte = WideCharToMultiByte(CP_OEMCP, 0, pws, -1, NULL, 0, NULL, NULL);
    if (iByte == 0) return false;

    char* ps;
    ps = (char*)malloc(iByte);
    if (NULL == ps) return false;

    WideCharToMultiByte(CP_OEMCP, 0, pws, -1, ps, iByte, NULL, NULL);

    s = std::string(ps);

    free(ps);

    return true;
}

bool s2ws(const std::string& s, std::wstring& ws)
{
    const char* ps = s.c_str();
    int iByte = ::MultiByteToWideChar(CP_OEMCP, 0, ps, -1, NULL, 0);
    if (iByte == 0) return false;

    wchar_t* pws;
    pws = (wchar_t*)malloc(iByte * sizeof(wchar_t));
    if (NULL == pws) return false;

    ::MultiByteToWideChar(CP_OEMCP, 0, ps, -1, pws, iByte);

    ws = std::wstring(pws);

    free(pws);

    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值