CString转换char* 网上方法很多,但是,有些博客提供的方法简直就是滥竽充数!!!
比如:
cstring temp("http");
char * ptr=(LPSTR)(LPCTSTR)temp;
该方法将导致运行的时候弹出堆栈错误,编译器连调试的机会都不给你直接抛出异常,然后程序死亡!
最安全的方法只有这一种:
CString str=_T("hello kitty 12345 hello jackson");
int len=str.GetLength();
char *buffer=new char[len+1];
memset(buffer,0,len+1);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)str, -1,NULL, 0, NULL, FALSE);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)str, -1,(LPSTR)buffer, len, NULL, FALSE);
buffer[len]='\0';
可以进行封装,比如:
char* CRtfControle::CString2Char(CString txt)
{
int len = txt.GetLength();
char* ctXt = new char[len+1];
memset(ctXt,0,len+1);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)txt, -1,NULL, 0, NULL, FALSE);
WideCharToMultiByte(CP_OEMCP, NULL, (LPCWSTR)txt, -1,(LPSTR)ctXt, len, NULL, FALSE);
ctXt[len]='\0';
return ctXt;
}
建议写博客的要有点鉴别能力,不要把错误的也抄下来!浪费大家时间!