首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

wofstream输入wstring老是坏流

2013-07-01 
wofstream输入wstring总是坏流std::wofstream streamstream.open(C:\\temp_info.txt)stream.imbue(std

wofstream输入wstring总是坏流
std::wofstream stream;
stream.open("C:\\temp_info.txt");
stream.imbue(std::locale("chs"));
for(std::size_t index=0;index!=8000;++index)
{
stream<<string_data<<std::endl;//string_data是一个字符串,大约有30KB左右
if(!stream)
throw std::runtime_error("unknow_error");//index大于3000左右就坏流了
}
[解决办法]


#include <boost/locale.hpp>//用boost的locale处理字符集转换
using boost::locale::conv;
ofstream file;
wstring string_data;//Unicode字符串
//...
//UTF-8编码:
    file << utf_to_utf<char>( string_data );//使用boost::locale::conv::utf_to_utf
//或者:
    file << from_utf( string_data, "utf-8" );//使用boost::locale::conv::from_utf


//GBK编码:
    file<<from_utf( string_data, "gbk" );//使用boost::locale::conv::from_utf


//UTF-16 LE
    for( std::wstring::const_iterator it = string_data.begin(); it != string_data.end(); ++ it )
    {
        file.put( static_cast<char>(*it) ).put( static_cast<char>((*it) >> 8) );
    }
    //static_cast是为了去掉编译警告,也可以不加。
    //或者用下面的代码,但不可靠:
    file.write( reinterpret_cast<char const *>(string_data.c_str()), string_data.size() * sizeof(wchar_t));

//UTF-16 BE:
    for( std::wstring::const_iterator it = string_data.begin(); it != string_data.end(); ++ it )
    {
        file.put( static_cast<char>((*it) >> 8) ).put( static_cast<char>(*it) );
    }

热点排行