Converting string or char* to wstring

Started by
2 comments, last by TANSTAAFL 18 years, 1 month ago
Is there any easy, built-in way to convert 8-bit strings (either std::string or char arrays/pointers) to a std::wstring. Or must I do it manually?
Advertisement
Since I program only Windows, I use MultiByteToWideChar. You can also use the ANSI function mbstowcs. Then if I need std::wstring i convert to that.

bool ConvertStringToUnicode(const char* cstr, wchar_t* wstr, int size){ // validate strings if(!cstr || cstr[0] == '\0') return false; if(!wstr || size <= 0) return false; // count number of elements to convert int elem = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cstr, -1, NULL, 0); if(!elem) return false; // convert string, clamping elem if buffer is size too small if(size < elem) elem = size; MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cstr, -1, wstr, elem); return true;}
a standards compliant way, specialization for boost::lexical_cast:

#ifndef HG_LEXICAL_CAST_H__#define HG_LEXICAL_CAST_H__//SHERIEF_20050806_NOLIB//DEP_BOOST#include <string>#include <locale>#include <boost/lexical_cast.hpp>namespace boost{	template<>    inline std::wstring lexical_cast<std::wstring, std::string>(const std::string& arg)    {		std::wstring result;		std::locale loc;		for(unsigned int i= 0; i < arg.size(); ++i)		{			result += std::use_facet<std::ctype<wchar_t> >(loc).widen(arg);		}		return result;    }	template<>    inline std::string lexical_cast<std::string, std::wstring>(const std::wstring& arg)    {		std::string result;		std::locale loc;		for(unsigned int i= 0; i < arg.size(); ++i)		{			result += std::use_facet<std::ctype<wchar_t> >(loc).narrow(arg);		}		return result;    }}#endif
wsprintf will convert narrow to wide character strings. %hs is the format specifier. from there, you can take your wide character pointer and make it into std::wstring.

Get off my lawn!

This topic is closed to new replies.

Advertisement