Click here to Skip to main content
14,741,830 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to convert a string to a Unicode String

char *p="D:\";
const WCHAR *pwcsName;

Now I want convert p(char *) to pwcsName(WCHAR *).
Can anybody suggest me how do this?

Is it done using "mbtowc" function or MultiByteToWideChar...

plz can someone suggest me code for that?
Updated 23-Mar-11 3:08am

for instance, this way:
  char *p="D:\\"; //just for proper syntax highlighting ..."
  const WCHAR *pwcsName;
  // required size
  int nChars = MultiByteToWideChar(CP_ACP, 0, p, -1, NULL, 0);
  // allocate it
  pwcsName = new WCHAR[nChars];
  MultiByteToWideChar(CP_ACP, 0, p, -1, (LPWSTR)pwcsName, nChars);
  // use it....
  // delete it
  delete [] pwcsName;

However, why don't you simply do
const WCHAR *pwcsName = L"D:\\";

Olivier Levrey 23-Mar-11 8:49am
Voted 5.
CPallini 23-Mar-11 8:50am
MartinTaylor 23-Mar-11 8:54am
Thank u.. I'll try it

the reason im not using -> const WCHAR *pwcsName = L"D:\\";
is that i'm retrieving string "D:\\" in some variable and them assigning it to
const WCHAR *pwcsName
CPallini 23-Mar-11 10:10am
If you're using MFC or ATL, have a look at 'ATL and MFC String Conversion Macros':
If you are 100% sure your char* string is ASCII only, the fastest and easiest way to "widen" it would be something like:

std::wstring w;
std::copy(p, p + strlen(p), back_inserter(w));
const WCHAR *pwcsName = w.c_str();
To Convert to unicode you need to use the following function:

MultiByteToWideChar -->[^]

example of MultiByteToWideChar:

MultiByteToWideChar(CP_UTF8, 0, buf, -1 , NULL, 0);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900