I am very new to C and pointers. I am trying to convert command line argument to wchar_t * . But somehow it is not giving proper output. What am I missing?
void fun(){
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale("en_US.utf8"));
char* mbstr = "f:\\mypath1\\mypath2\\mypath3";
wstring reposPath;
char *c_ReposPathString = (char*)mbstr;
size_t c_ReposPathStringSize= 0;
if(c_ReposPathString)
{
c_ReposPathStringSize = 2*(strlen(c_ReposPathString)+1);
}
wchar_t *w_ReposPathChar = new wchar_t[c_ReposPathStringSize];
if(w_ReposPathChar)
{
mbstowcs(w_ReposPathChar, c_ReposPathString, c_ReposPathStringSize);
}
reposPath = w_ReposPathChar;
printf("%s", (char *)reposPath.c_str());
free(w_ReposPathChar);
}
when I print length of w_path, it shows 1. But argv[1] has more than one character it it.
You can't simply re-cast a
wchar_tstring to acharstring and expect it to work, as there may (will) be manywchar_tvalues that have their upper byte as zero (which will be seen as a terminator, after the cast).So, instead of:
which sees a 'false' nul-terminator after the
f, simply print thewchar_tstring for what it is:Also, you have a
constmissing in your declaration ofmbstr, which should be this:and you don't need to allocate twice the number of
charfor yourwchar_tbuffer, so this will suffice:Feel free to ask for further clarification and/or explanation.