Christopher wrote, On 19.2.2009 8:05:
Googled it and saw several ways to do it. None of which seemed to be
standard C++. Except this one, but it is only from string to wstring.
How do I go back again?
Also can someone verify this is OK?
I am not sure but I do not think that widen() does what what you need but I
am not sure.
//----------------------------------------------------------------------------
std::wstring StringToWString(const std::string & s)
{
typedef std::ctype<wchar_t> CT;
std::wstring wide(s.length(), L'\0');
CT const & ct = std::_USE(std::locale(), CT);
ct.widen(&s[0], &s[0] + s.size(), &wide[0]);
return wide;
}
I have been using the following:
void
towstring_internal (std::wstring & outstr, const char * src, size_t size,
std::locale const & loc)
{
typedef std::codecvt<wchar_t, char, mbstate_t> CodeCvt;
const CodeCvt & cdcvt = std::use_facet<CodeCvt>(loc);
mbstate_t state;
clear_mbstate (state);
char const * from_first = src;
size_t const from_size = size;
char const * const from_last = from_first + from_size;
char const * from_next = from_first;
std::vector<wchar_t> dest (from_size);
wchar_t * to_first = &dest.front ();
size_t to_size = dest.size ();
wchar_t * to_last = to_first + to_size;
wchar_t * to_next = to_first;
CodeCvt::result result;
size_t converted = 0;
while (true)
{
result = cdcvt.in (
state, from_first, from_last,
from_next, to_first, to_last,
to_next);
// XXX: Even if only half of the input has been converted the
// in() method returns CodeCvt:
k. I think it should return
// CodeCvt:
artial.
if ((result == CodeCvt:
artial || result == CodeCvt:
k)
&& from_next != from_last)
{
to_size = dest.size () * 2;
dest.resize (to_size);
converted = to_next - to_first;
to_first = &dest.front ();
to_last = to_first + to_size;
to_next = to_first + converted;
continue;
}
else if (result == CodeCvt:
k && from_next == from_last)
break;
else if (result == CodeCvt::error
&& to_next != to_last && from_next != from_last)
{
clear_mbstate (state);
++from_next;
from_first = from_next;
*to_next = L'?';
++to_next;
to_first = to_next;
}
else
break;
}
converted = to_next - &dest[0];
outstr.assign (dest.begin (), dest.begin () + converted);
}