C编程经典类型转换

 

一,Convert between ANSI and UNICODE strings

 

Details Refer to 

http://www.codeguru.com/forum/showthread.php?t=231165

 

 

(1) ANSI to UNICODE:

 

Char* -> LPCWSTR

 

For example:

 

char *ansistr = "Hello"
int lenA = lstrlenA(ansistr);
int lenW;
BSTR unicodestr;

lenW = ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, 0, 0);
if (lenW > 0)
{
  // Check whether conversion was successful
  unicodestr = ::SysAllocStringLen(0, lenW);
  ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, unicodestr, lenW);
}
else
{
  // handle the error
}

// when done, free the BSTR
::SysFreeString(unicodestr);

 

(2)UNICODE to ANSI:
LPCWSTR->Char*
 
  
二,CString, String, Char*, int 类型转换

char* 转 int 
#include <stdlib.h>

int atoi(const char *nptr); 
long atol(const char *nptr);

 

char* 转 string  
string s(char *);  
你的只能初始化,在不是初始化的地方最好还是用assign().

 

 

string 转 char *  
char *p = string.c_str(); 

string aa("aaa"); 
char *c=aa.c_str(); 
string mngName; 
char t[200]; 
memset(t,0,200); 
strcpy(t,mngName.c_str());

 

string 转 CString  
CString.format("%s", string.c_str());  

 

char 转 CString  
CString.format("%s", char*);  

 

char 转 string  
string s(char *);  

 

string 转 char *  
char *p = string.c_str();  

 

CString 转 string  
string s(CString.GetBuffer()); 

 

 

未完待续

你可能感兴趣的:(编程,c,String)