سؤال

I am trying to convert a char string to a wchar string.

In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.

char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;

But it prints just c

Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?

هل كانت مفيدة؟

المحلول

mbtowc converts only a single character. Did you mean to use mbstowcs?

Typically you call this function twice; the first to obtain the required buffer size, and the second to actually convert it:

#include <cstdlib> // for mbstowcs

const char* mbs = "c:\\user";
size_t requiredSize = ::mbstowcs(NULL, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
if(::mbstowcs(wcs, mbs, requiredSize + 1) != (size_t)(-1))
{
    // Do what's needed with the wcs string
}
delete[] wcs;

If you rather use mbstowcs_s (because of deprecation warnings), then do this:

#include <cstdlib> // also for mbstowcs_s

const char* mbs = "c:\\user";
size_t requiredSize = 0;
::mbstowcs_s(&requiredSize, NULL, 0, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
::mbstowcs_s(&requiredSize, wcs, requiredSize + 1, mbs, requiredSize);
if(requiredSize != 0)
{
    // Do what's needed with the wcs string
}
delete[] wcs;

Make sure you take care of locale issues via setlocale() or using the versions of mbstowcs() (such as mbstowcs_l() or mbstowcs_s_l()) that takes a locale argument.

نصائح أخرى

why are you using C code, and why not write it in a more portable way, for example what I would do here is use the STL!

std::string  src = std::string("C:\\user") +
                   std::string(" 1");
std::wstring dne = std::wstring(src.begin(), src.end());

wcout << dne;

it's so simple it's easy :D

L"Hello World"

the prefix L in front of the string makes it a wide char string.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top