How do I convert a char string to a wchar_t string?
Solution 1
Does this little function help?
#include <cstdlib>
int mbstowcs(wchar_t *out, const char *in, size_t size);
Also see the C++ reference
Solution 2
If you don't want to link against the C runtime library, use the MultiByteToWideChar API call, e.g:
const size_t WCHARBUF = 100;
const char szSource[] = "HELLO";
wchar_t wszDest[WCHARBUF];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSource, -1, wszDest, WCHARBUF);
Solution 3
the Windows SDK specifies 2 functions in kernel32.lib for converting strings from and to a wide character set. those are MultiByteToWideChar()
and WideCharToMultiByte()
.
please note that, unlike the function name suggest, the string does not necessarily use a multi-byte character set, but can be a simple ANSI string. alse note that those functions understand UTF-7 and UTF-8 as a multi-byte character set. the wide char character set is always UTF-16.
Solution 4
schnaader's answer use the conversion defined by the current C locale, this one uses the C++ locale interface (who said that it was simple?)
std::wstring widen(std::string const& s, std::locale loc)
{
std::char_traits<wchar_t>::state_type state = { 0 };
typedef std::codecvt<wchar_t, char, std::char_traits<wchar_t>::state_type >
ConverterFacet;
ConverterFacet const& converter(std::use_facet<ConverterFacet>(loc));
char const* nextToRead = s.data();
wchar_t buffer[BUFSIZ];
wchar_t* nextToWrite;
std::codecvt_base::result result;
std::wstring wresult;
while ((result
= converter.in
(state,
nextToRead, s.data()+s.size(), nextToRead,
buffer, buffer+sizeof(buffer)/sizeof(*buffer), nextToWrite))
== std::codecvt_base::partial)
{
wresult.append(buffer, nextToWrite);
}
if (result == std::codecvt_base::error) {
throw std::runtime_error("Encoding error");
}
wresult.append(buffer, nextToWrite);
return wresult;
}
Related videos on Youtube
justinhj
I'm a functional programming fanatic working as a Scala consultant enter link description here
Updated on June 04, 2022Comments
-
justinhj almost 2 years
I have a string in
char*
format and would like to convert it towchar_t*
, to pass to a Windows function.-
MSalters over 14 yearsMost Windows functions actually come in two flavors, a "A" and "W" version. E.g. MessageBoxA / MessageBoxW, with a macro "MessageBox" refering to one of the two. But if you use the explicit
MessageBoxA
name, you can pass achar*
independent of project settings.
-
-
asveikau over 14 yearsDepending on where your string comes from, you might also want to consider CP_UTF8 instead of CP_ACP. It can store all Unicode characters.
-
netskink almost 7 yearsFor me on windows10 with visual studio 2017, CP_ACP worked. CP_UTF8 did not.
-
user2498772 almost 2 yearsThis function is deprecated.