CString 和 char*的转换

CString 是一种很特殊的 C++ 对象,它里面包含了三个值:一个指向某个数据缓冲区的指针、一个是该缓冲中有效的字符记数(它是不可存取的,是位于 CString 地址之下的一个隐藏区域)以及一个缓冲区长度。 有效字符数的大小可以是从0到该缓冲最大长度值减1之间的任何数(因为字符串结尾有一个NULL字符)。字符记数和缓冲区长度被巧妙隐藏。

(1) char*转换成CString

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

         char chArray[] = "Char test";
        TCHAR * p = _T("Char test");( 或LPTSTR p = _T("Char test");)
         CString theString = chArray;
         theString.Format(_T("%s"), chArray);
         theString = p;

(2) CString转换成char*

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

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

       CString theString( (_T("Char test "));
        LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

  方法二,使用strcpy。例如:

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

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

  方法三,使用CString::GetBuffer。

        如果你需要修改 CString 中的内容,它有一个特殊的方法可以使用,那就是 GetBuffer,它的作用是返回一个可写的缓冲指针。 如果你只是打算修改字符或者截短字符串,例如:
       CString s(_T("Char test "));
        LPTSTR p = s.GetBuffer();

       LPTSTR dot = strchr(p, ''.'');

         // 在这里添加使用p的代码

         if(p != NULL)

        *p = _T('');
         s.ReleaseBuffer();                     // 使用完后及时释放,以便能使用其它的CString成员函数

        在 GetBuffer 和 ReleaseBuffer 之间这个范围,一定不能使用你要操作的这个缓冲的 CString 对象的任何方法。因为 ReleaseBuffer 被调用之前,该 CString 对象的完整性得不到保障。

文章转自:http://www.cnblogs.com/thankgoodness/articles/1323878.html

 

类别:vc综合 | 添加到搜藏 | 浏览( 29) | 评论 (0) <script> /*<![CDATA[*/ var pre = [true,'vc++制作盗取qq密码的另类方法', 'vc++制作盗取qq密码的另类方法','/dqf8/blog/item/6085dd07e9acf6c57a894769.html']; var post = [true,'GetSysColor()函数','GetSysColor()函数', '/dqf8/blog/item/a67488cbead3a7f552664fdb.html']; if(pre[0] || post[0]){ document.write('<div style="height:5px;line-height:5px;">&nbsp;</div><div id="in_nav">'); if(pre[0]){ document.write('上一篇:<a href="' + pre[3] + '" title="' + pre[1] + '">' + pre[2] + '</a>&nbsp;&nbsp;&nbsp;&nbsp;'); } if(post[0]){ document.write('下一篇:<a href="' + post[3] + '" title="' + post[1] + '">' + post[2] + '</a>'); } document.write('</div>'); } /*]]>*/ </script>
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值