C ++ - 将istream_iterator与wstringstream一起使用

时间:2014-01-06 21:08:06

标签: c++ unicode std

我正在尝试为我编写的程序添加Unicode支持。我的ASCII代码已编译并具有以下行:

std::stringstream stream("abc");
std::istream_iterator<std::string> it(stream);

我将其转换为:

std::wstringstream stream(L"abc");
std::istream_iterator<std::wstring> it(stream);

我在istream_iterator构造函数中收到以下错误:

error C2664: 'void std::vector<_Ty>::push_back(std::basic_string<_Elem,_Traits,_Alloc> &&)' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Alloc>' to 'std::basic_string<_Elem,_Traits,_Alloc> &&'
1>          with
1>          [
1>              _Ty=std::wstring,
1>              _Elem=wchar_t,
1>              _Traits=std::char_traits<wchar_t>,
1>              _Alloc=std::allocator<wchar_t>
1>          ]
1>          and
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          and
1>          [
1>              _Elem=wchar_t,
1>              _Traits=std::char_traits<wchar_t>,
1>              _Alloc=std::allocator<wchar_t>
1>          ]
1>          Reason: cannot convert from 'std::basic_string<_Elem,_Traits,_Alloc>' to 'std::basic_string<_Elem,_Traits,_Alloc>'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
1>          and
1>          [
1>              _Elem=wchar_t,
1>              _Traits=std::char_traits<wchar_t>,
1>              _Alloc=std::allocator<wchar_t>
1>          ]
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

将上面的代码转换为Unicode的正确方法是什么?

感谢。

P.S。

我正在运行Visual Studio 2012

1 个答案:

答案 0 :(得分:9)

尝试:

std::wstringstream stream(L"abc");
std::istream_iterator<std::wstring, wchar_t> it(stream);

...看看它是否效果不佳。

关于评论:不,这对于UTF-8来说不是。它(或多或少)直接从包含UTF-16的文件读入包含UTF-16的字符串。根据编译器及其用于wchar_t的大小,可能是UTF-32,但(可能)不会是UTF-8。

要从文件中读取UTF-8并转换为UTF-32以供内部使用,您可能需要查看Boost.locale,其中包含一个utf-to-utf codecvt方面。