• 把CString转化为char*


    转:http://blog.sina.com.cn/s/blog_58e19ae7010003jt.html

    正确方法:
    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;就够了!

  • 相关阅读:
    Map集合
    MySql函数之CONCAT、CONCAT_WS、GROUP_CONCAT函数详解
    mysql字符串转数字排序
    阿里巴巴Json工具Fastjson教程
    tf.set_shape
    numpy切片X[:,0]和X[:,1]
    numpy索引和切片 np.newaxis np.arange
    tf.cast()用于张量数据类型的转换
    自监督
    在神经网络中bias偏置有什么作用?
  • 原文地址:https://www.cnblogs.com/jiu0821/p/4396072.html
Copyright © 2020-2023  润新知