3

I have programmed some code but there is some problem. In this codes i am trying to convert string to wstring. But this string have "█" characters. This character have 219 ascii code. This conversion getting error.

In my code: string strs= "█and█something else"; wstring wstr(strs.begin(),strs.end());

After debugging, I am getting result like this ?and?something else

How do I correct this problem?

Thanks...

Mehmet
  • 43
  • 1
  • 1
  • 3
  • Here's an old [pre-C++11 answer](http://stackoverflow.com/a/7159944/596781). With C++11 there's a slightly easier way using a built-in codecvt facet. – Kerrek SB Aug 25 '14 at 11:52

1 Answers1

1

The C-library solution for converting between the system's narrow and wide encoding use the mbsrtowcs and wcsrtombs functions from the <cwchar> header. I've spelt this out in this answer.

In C++11, you can use the wstring_convert template instantiated with a suitable codecvt facet. Unfortunately this requires some custom rigging, which is spelt out on the cppreference page.

I've adapted it here into a self-contained example which converts a wstring to a string, converting from the system's wide into the system's narrow encoding:

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>

// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
template <typename Facet>
struct deletable_facet : Facet
{
    using Facet::Facet;
};

int main()
{
    std::wstring_convert<
        deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv;

    std::wstring ws(L"Hello world.");
    std::string ns = conv.to_bytes(ws);

    std::cout << ns << std::endl;
}
Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks you for interesting. But I must convert string to wstring. I not sure that Is Your code convert string to wstring. I may try to this code. – Mehmet Aug 25 '14 at 12:11
  • @Mehmet: Look up the documentation. `to_bytes` and `from_bytes`. – Kerrek SB Aug 25 '14 at 12:14