首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

CString型转换为char型,请教什么办法或函数

2012-02-14 
CString型转换为char型,请问什么办法或函数?CString型转换为char型,请问什么办法或函数?[解决办法]CString

CString型转换为char型,请问什么办法或函数?
CString型转换为char型,请问什么办法或函数?

[解决办法]
CString Str_today;
char data[512];
ZeroMemory(data,512);
Str_today= "杨献奇 ";
memcpy(data,Str_today,Str_today.GetLength());
CString strtest;
strtest=data;
MessageBox(strtest);
这个我试过可以的
[解决办法]
1) char*转换成CString

  若将char*转换成CString,除了直接赋值外,还可使用CString::Format进行。例如:

char chArray[] = "This is a test ";
char * p = "This is a test ";

  或

LPSTR p = "This is a test ";

  或在已定义Unicode应的用程序中

TCHAR * p = _T( "This is a test ");

  或

LPTSTR p = _T( "This is a test ");
CString theString = chArray;
theString.Format(_T( "%s "), chArray);
theString = p;

(2) CString转换成char*

  若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:

  方法一,使用强制转换。例如:

CString theString( "This is a test " );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

  方法二,使用strcpy。例如:

CString theString( "This is a test " );
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);

  需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。

  方法三,使用CString::GetBuffer。例如:

CString s(_T( "This is a test "));
LPTSTR p = s.GetBuffer();
// 在这里添加使用p的代码
if(p != NULL) *p = _T( '\0 ');
s.ReleaseBuffer();
// 使用完后及时释放,以便能使用其它的CString成员函数

热点排行