Click here to Skip to main content
15,946,525 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?
Posted
Updated 23-Mar-11 2:08am
v2

for instance, this way:
C++
  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
C++
const WCHAR *pwcsName = L"D:\\";


?
 
Share this answer
 
v2
Comments
Olivier Levrey 23-Mar-11 8:49am    
Voted 5.
CPallini 23-Mar-11 8:50am    
Thanks
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': http://msdn.microsoft.com/en-us/library/87zae4a3.aspx
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();
 
Share this answer
 
To Convert to unicode you need to use the following function:

MultiByteToWideChar -->

http://msdn.microsoft.com/en-us/library/dd319072(v=vs.85).aspx[^]

example of MultiByteToWideChar:

MultiByteToWideChar(CP_UTF8, 0, buf, -1 , NULL, 0);
 
Share this answer
 
v2

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