Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Using istream_iterator with wstringstream

Tags:

c++

std

unicode

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

like image 421
Benjy Kessler Avatar asked Jan 06 '14 21:01

Benjy Kessler


1 Answers

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.

like image 97
Jerry Coffin Avatar answered Sep 20 '22 11:09

Jerry Coffin