3

I'm trying to convert a C++ string to a wstring. I found the following code, that seems to deal with accents, which is what I'm looking for.

std::wstring widen(const std::string& s)
{
    std::vector<wchar_t> buffer(s.size());
    std::locale loc("fr_FR");
    std::use_facet< std::ctype<wchar_t> >(loc).widen(s.data(), s.data() + s.size(), &buffer[0]);

    return std::wstring(&buffer[0], buffer.size());
}

Source

Unfortunately, the code crashes for any other loc value than C or POSIX. This problem has already been discussed, without success, here: std::locale breakage on MacOS 10.6 with LANG=en_US.UTF-8, here or here.

Is there any workaround or an other way to do this ?

Community
  • 1
  • 1
Klaus
  • 1,241
  • 4
  • 14
  • 31
  • Can you fix the title? It reads as if you want to convert wstring -> string. Your problem description however is string -> wstring. – rnicholson Jan 17 '10 at 14:15

1 Answers1

1

The simplest would be

std::wstring w( s.begin(), s.end() );

... but to preserve accents you'd need codecvt however, this example might be useful.

Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
  • As the example uses 'std::locale loc (std::cout.getloc (), new ex_codecvt);' won't it just bug the same way ? – Klaus Jan 16 '10 at 12:27