views:

257

answers:

2

Hello, 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: http://stackoverflow.com/questions/1745045/stdlocale-breakage-on-macos-10-6-with-langenus-utf-8, here or here.

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

+1  A: 

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
As the example uses 'std::locale loc (std::cout.getloc (), new ex_codecvt);' won't it just bug the same way ?
Klaus
+1  A: 

Consider using boost::lexical_cast.

See: lexical_cast

Polybos