C++ - Using istream_iterator with wstringstream

狂风中的少年 提交于 2020-01-23 06:14:20

问题


I am trying to add Unicode support to a program that I wrote. My ASCII code compiled and had the following lines:

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

I converted this to:

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

I get the following error in the istream_iterator constructor:

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

What is the correct way to convert the code above to Unicode?

Thanks.

P.S.

I am running Visual Studio 2012


回答1:


Try:

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

...and see if it doesn't work better.

Regarding comments: No, this is not for UTF-8. It's to (more or less) directly read from a file containing UTF-16 into a string containing UTF-16. Depending on the compiler and what size it uses for wchar_t, that could be UTF-32 instead, but (probably) won't ever be UTF-8.

To read UTF-8 from the file and convert to something like UTF-32 for internal use, you might want to look at Boost.locale, which includes a utf-to-utf codecvt facet.



来源:https://stackoverflow.com/questions/20959300/c-using-istream-iterator-with-wstringstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!