解决啦!Windows自制u16cout来啦!

本文介绍了如何在Windows系统中,由于缺乏内置的u16cout和u32cout,作者自行实现这一功能的过程。由于在Windows中char16_t与wchar_t等价,使得这个实现成为可能。在Unix系统中,可以将'u16'替换为'u32'进行相应调整。通过这个方法,读者可以在自己的项目中支持Unicode输出。

为了支持Unicode,string便有了

  template<class _CharT>
    struct char_traits;

  template<typename _CharT, typename _Traits = char_traits<_CharT>,
           typename _Alloc = allocator<_CharT> >
    class basic_string;

  template<> struct char_traits<char>;

  /// A string of @c char
  typedef basic_string<char>    string;   

#ifdef _GLIBCXX_USE_WCHAR_T
  template<> struct char_traits<wchar_t>;

  /// A string of @c wchar_t
  typedef basic_string<wchar_t> wstring;   
#endif

#if ((__cplusplus >= 201103L) \
     && defined(_GLIBCXX_USE_C99_STDINT_TR1))

  template<> struct char_traits<char16_t>;
  template<> struct char_traits<char32_t>;

  /// A string of @c char16_t
  typedef basic_string<char16_t> u16string; 

  /// A string of @c char32_t
  typedef basic_string<char32_t> u32string; 

#endif

u16string
u32string
可是,没有
u16cout
u32cout

所以,
还是自己做吧。

#include<iostream>
using namespace std;
typedef basic_ostream<char16_t> u16ostream;
typedef basic_streambuf<char16_t> u16streambuf;
u16ostream u16cout(reinterpret_cast<u16streambuf*>(wcout.rdbuf()));

这还是托Windows里char16_t == wchar_t的缘故…
如果你是unix,请将’u16’改成’u32’。
试试

#include<io.h>
#include<fcntl.h>
int main(){
_setmode(_fileno(stdout),_O_U16TEXT);
u16cout<<u"look at the \u08a6";
}

结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值