• Advertisement
Sign in to follow this  

Converting string or char* to wstring

This topic is 4373 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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;
}






Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement