Click here to Skip to main content
Sign Up to vote bad
good
See more: C++C
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 23 Mar '11 - 2:00
Edited 23 Mar '11 - 2:08


3 solutions

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:\\";
 
?
  Permalink  
Comments
Olivier Levrey - 23 Mar '11 - 8:49
Voted 5.
CPallini - 23 Mar '11 - 8:50
Thanks
klusner - 23 Mar '11 - 8:54
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:10
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
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);
  Permalink  
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();
  Permalink  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 OriginalGriff 253
1 Rohan Leuva 220
2 Sergey Alexandrovich Kryukov 208
3 Abhinav S 168
4 Mahesh Bailwal 165
0 Sergey Alexandrovich Kryukov 8,494
1 OriginalGriff 6,799
2 CPallini 3,603
3 Rohan Leuva 2,923
4 Maciej Los 2,234


Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 23 Mar 2011
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid