终于把CString转化为char*了
生活随笔
收集整理的這篇文章主要介紹了
终于把CString转化为char*了
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
看了無數(shù)帖子,試了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);//可以執(zhí)行,但codefile的值為空
參考資料:
CString轉(zhuǎn)化為char?
CString::GetAt 這個返回一個 char
如果是要char *
可以用CString:Getbuffer 這個返回一個 char *
其實還可以強制轉(zhuǎn)化:
LPCTSTR pch;
CString str("123456");
pch = (LPCTSTR)str;
上面的代碼實際上就是先讓系統(tǒng)執(zhí)行了一次強制轉(zhuǎn)化的結(jié)果,所以其實有點多此一舉了……
但是這樣做更安全一些,因為char *pBuffer = (LPSTR)(LPCTSTR)str;這樣轉(zhuǎn)換,只是讓char指針指向了ctring的內(nèi)存地址,如果對char進行了寫操作的話,因為跨越了cstring的封裝,有可能導(dǎo)致cstring對象的混亂,所以重新copy一個新的給char指針,可以做到更安全!
如果只讀不寫,用char *pBuffer = (LPSTR)(LPCTSTR)str;就夠了!
正確方法:
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);//可以執(zhí)行,但codefile的值為空
參考資料:
CString轉(zhuǎn)化為char?
CString::GetAt 這個返回一個 char
如果是要char *
可以用CString:Getbuffer 這個返回一個 char *
其實還可以強制轉(zhuǎn)化:
LPCTSTR pch;
CString str("123456");
pch = (LPCTSTR)str;
上面的代碼實際上就是先讓系統(tǒng)執(zhí)行了一次強制轉(zhuǎn)化的結(jié)果,所以其實有點多此一舉了……
但是這樣做更安全一些,因為char *pBuffer = (LPSTR)(LPCTSTR)str;這樣轉(zhuǎn)換,只是讓char指針指向了ctring的內(nèi)存地址,如果對char進行了寫操作的話,因為跨越了cstring的封裝,有可能導(dǎo)致cstring對象的混亂,所以重新copy一個新的給char指針,可以做到更安全!
如果只讀不寫,用char *pBuffer = (LPSTR)(LPCTSTR)str;就夠了!
總結(jié)
以上是生活随笔為你收集整理的终于把CString转化为char*了的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MFC使用剪贴板
- 下一篇: 关于UAC执行级别的研究