彻底解密C++宽字符:5、利用fstream转换

C++的流和本地化策略集

BS在设计C++流的时候希望其具备智能化,并且是可扩展的智能化,也就是说,C++的流可以“读懂”一些内容。比如:

std::cout  <<   123   <<   " ok "   <<  std::endl;
这句代码中,std::cout是能判断出123是int而"ok"是const char[3]。利用流的智能,甚至可以做一些基础类型的转换,比如从int到string,string到int:
std:: string  str( " 123 " );
std::stringstream sstr(str);
int  i;
sstr  >>  i;
int  i  =   123 ;
std::stringstream sstr;
sstr  <<  i;
std:: string  str  =  sstr.str();
尽管如此,C++并不满足,C++甚至希望流能“明白”时间,货币的表示法。而时间和货币的表示方法在世界范围内是不同的,所以,每一个流都有自己的locale在影响其行为,C++中叫做激活(imbue,也有翻译成浸染)。而我们知道,每一个locale都有多个facet,这些facet并非总是被use_facet使用的。决定使用哪些facet的,是流的缓存basic_streambuf及其派生类basic_stringbuf和basic_filebuf。我们要用到的facet是codecvt,这个facet只被basic_filebuf使用——这就是为什么只能用fstream来实现宽窄转换,而无法使用sstream来实现的原因。
头文件:
// filename string_wstring_fstream.hpp
#ifndef STRING_WSTRING_FSTREAM_HPP
#define  STRING_WSTRING_FSTREAM_HPP

#include  < string >

const  std::wstring s2ws( const  std:: string &  s);
const  std:: string  ws2s( const  std::wstring &  s);

#endif
实现:
#include  < string >
#include  < fstream >
#include  " string_wstring_fstream.hpp "

const  std::wstring s2ws( const  std:: string &  s)
{
    std::locale sys_loc( "" );

    std::ofstream ofs( " cvt_buf " );
    ofs  <<  s;
    ofs.close();

    std::wifstream wifs( " cvt_buf " );
    wifs.imbue(sys_loc);
    std::wstring wstr;
    wifs  >>  wstr;
    wifs.close();

     return  wstr;
}

const  std:: string  ws2s( const  std::wstring &  s)
{
    std::locale sys_loc( "" );

    std::wofstream wofs( " cvt_buf " );
    wofs.imbue(sys_loc);
    wofs  <<  s;
    wofs.close();

    std::ifstream ifs( " cvt_buf " );
    std:: string  str;
    ifs  >>  str;
    ifs.close();

     return  str;
}
在窄到宽的转化中,我们先使用默认的本地化策略集(locale)将s通过窄文件流ofs传入文件,这是char到char的传递,没有任何转换;然后我们打开宽文件流wifs,并用系统的本地化策略集(locale)去激活(imbue)之,流在读回宽串wstr的时候,就是char到wchar_t的转换,并且因为激活了sys_loc,所以实现标准窄到宽的转换。
在宽到窄的转化中,我们先打开的是宽文件流wofs,并且用系统的本地化策略集sys_loc激活(imbue)之,这时候,因为要写的文件cvt_buf是一个外部编码,所以执行了从wchar_t到char的标准转换。读回来的文件流从char到char,不做任何转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值