文档详情

数据转换与操作.doc

发布:2017-12-10约2.86万字共41页下载文档
文本预览下载声明
2.2. 2.2 2.2.CString及string,char *与其他 2.2.CString及string,char *与其他数据类型的转换和操作 (1)CString,string,char*的综合比较(这部分CSDN上的作者joise的文章 CString,string,char*的综合比较写的很详细,请大家在仔细阅读他的文章. 地址: /joise/ 或参考附录: (2)转换: ●数学类型与CString相互转化 数学类型转化为CString 可用Format函数,举例: CString s; int i = 64; s.Format(%d, i) CString转换为数学类型:举例 CString strValue(1.234); double dblValue; dblValue = atof((LPCTSTR)strValue); ●CString与char*相互转换举例 CString strValue(“Hello”); char *szValue; szValue=strValue.GetBuffer(szValue); 也可用(LPSTR)(LPCTSTR)对CString// 进行强制转换. szValue=(LPSTR)(LPCTSTR)strValue; 反过来可直接赋值: char *szChar=NULL; CString strValue; szChar=new char[10]; memset(szChar,0,10); strcpy(szChar,”Hello”); strValue=szChar; ●CString 与 BSTR 型转换 CString 型转化成 BSTR 型 当我们使用 ActiveX 控件编程时,经常需要用到将某个值表示成 BSTR 类型.BSTR 是一种记数字符串,Intel平台上的宽字符串(Unicode),并且可以包含嵌入的 NULL 字符。 可以调用 CString 对象的 AllocSysString 方法将 CString 转化成 BSTR: CString str; str = ; // whatever BSTR bStr = str.AllocSysString(); BSTR型转换为CString 如果你在 UNICODE 模式下编译代码,你可以简单地写成: CString convert(BSTR bStr) { if(bStr == NULL) return CString(_T()); CString s(bStr); // in UNICODE mode return s; } 如果是 ANSI 模式 CString convert(BSTR b) { CString s; if(b == NULL) return s; // empty for NULL BSTR #ifdef UNICODE s = b; #else LPSTR p = s.GetBuffer(SysStringLen(b) + 1); ::WideCharToMultiByte(CP_ACP, // ANSI Code Page 0, // no flags b, // source widechar string -1, // assume NUL-terminated p, // target buffer SysStringLen(b)+1, // target buffer length NULL, // use system default char NULL); // dont care if default used s.ReleaseBuffer(); #endif return s; } ●VARIANT 型转化成 CString 型 VARIANT 类型经常用来给 COM 对象传递参数,或者接收从 COM 对象返回的值。你也能自己编写
显示全部
相似文档