现在的位置: 首页 > 综合 > 正文

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

2014年10月15日 ⁄ 综合 ⁄ 共 1790字 ⁄ 字号 评论关闭

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,不做任何转换。

抱歉!评论已关闭.