Sign in to follow this  

Converting string or char* to wstring

This topic is 4302 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

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[i]);
}
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[i]);
}
return result;
}
}

#endif

Share this post


Link to post
Share on other sites

This topic is 4302 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this