CString stirng char*

终于把CString转化为char*了
转载

看了无数帖子,试了n种方法,终于成功了!
正确方法:
CString m_Head;
char *codefile;
codefile=(LPSTR)(LPCTSTR)m_Head;//正确,想办法去掉后缀
补充:
int fnlen = m_Head.GetLength() ; //strcspn(str,".");
codefile=new char[fnlen+4];
codefile=(LPSTR)(LPCTSTR)m_Head;//正确,想办法去掉后缀
for(int i=fnlen-1;i>3;i--)//去掉文件后缀.pas
{if((codefile[i]=='s')&&(codefile[i-1]=='a')&&(codefile[i-2]
=='p')&&(codefile[i-3]=='.'))
{codefile[i]=codefile[i-1]=codefile[i-2]=codefile[i-3]=' ';
break;}
}
错误方法1:int fnlen = m_Head.GetLength() ; //strcspn(str,".");
codefile=new char[fnlen+4];
int i=0;//名字不正确,但是不为空。
for (; i<fnlen;i++)
codefile[i]=m_Head[i];
codefile[fnlen]=0;
错误方法2:
strcpy(codefile,m_Head.GetBuffer(fnlen)); //这句会让程序意外中止!
m_Head.ReleaseBuffer(fnlen);
错误方法3:
strcpy(codefile,m_Head);//这句也会让程序意外中止!
错误方法4:
codefile=m_Head.GetBuffer(fnlen);//可以执行,但codefile的值为空

参考资料:
CString转化为char?
CString::GetAt 这个返回一个 char

如果是要char *
可以用CString:Getbuffer 这个返回一个 char *
其实还可以强制转化:
LPCTSTR pch;
CString str("123456");
pch = (LPCTSTR)str;
上面的代码实际上就是先让系统执行了一次强制转化的结果,所以其实有点多此一举了……
但是这样做更安全一些,因为char *pBuffer = (LPSTR)(LPCTSTR)str;这样转换,只是让char指针指向了ctring的内存地址,如果对char进行了写操作的话,因为跨越了cstring的封装,有可能导致cstring对象的混乱,所以重新copy一个新的给char指针,可以做到更安全!

如果只读不写,用char *pBuffer = (LPSTR)(LPCTSTR)str;就够了!

--------------------------------------------------

CString和string的互相转换
 
CString->std::string 例子:

CString strMfc=“test“;

std::string strStl;

strStl=strMfc.GetBuffer(0);

std::string->CString  例子:

CString strMfc;

std::string strStl=“test“;

strMfc=strStl.c_str();


-----------------------------------------------------------


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值