Archives mensuelles pour juillet 2010

How to safely convert a wide string into a narrow string (and vice-versa) ?

Irrlicht relies on wide strings (irr::core::stringw / std::wstring) for the GUI system but I had to convert some of them into narrow strings (std::string for instance) for the game.
So I looked on the internet for various solutions but there didn’t seem to be a general and clean one. Snippets did always call a fixed-size buffer which I din’t want to resort to.
That’s when I discovered this very neat C++ project (just a few headers). It makes the conversion through iterators and seems robust (until now I haven’t met any problem).

Here is the code I use :

inline void
convertIntoNarrowString(const std::wstring& original, std::string& converted)
{
utf8::utf16to8(original.begin(),original.end(), std::back_inserter(converted) );
}

inline void
convertIntoWideString(const std::string& original, std::wstring& converted)
{
utf8::utf8to16(original.begin(),original.end(), std::back_inserter(converted) );
}