H'H H'H - 2 months ago 16
C++ Question

Better way to convert const wchar_t * to const std::basic_string<char_t>

I am wondering if there is easier way (less verbose) to convert

const char_t*
to
std::string_t
rather than below:

typedef wchar_t char_t;
typedef basic_string<char_t> string_t;

std::wstring ws(script_->GetName()); //GetName() returns const char_t*
const std::string wsStr(ws.begin(), ws.end());
const string_t script_name(wsStr.begin(), wsStr.end());


Any help would be appreciated.

EDIT

#ifdef OS_WIN
#include <tchar.h>
typedef wchar_t char_t;
#define CHAR_WIDE
#else
typedef char char_t;

Answer

From the typedefs that you have, it boils down that you wanna to convert a wchar_t const* string to a std::basic_string<wchar_t>. You could just pass the range of the wchar_t const* string into the constructor of std::basic_string<wchar_t>:

wchar_t const *str = L"abcdefgh";
const std::basic_string<wchar_t> script_name(str, str + std::char_traits<wchar_t>::length(str));

Live Demo

Comments