600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > char装cstring_MFC中char* string和CString之间的转换-阿里云开发者社区

char装cstring_MFC中char* string和CString之间的转换-阿里云开发者社区

时间:2018-11-16 10:44:41

相关推荐

char装cstring_MFC中char* string和CString之间的转换-阿里云开发者社区

一、将CString类转换成char*(LPSTR)类型

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

CString theString( "This is a test" );

LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

方法二,使用strcpy。例如:

CString theString( "This is a test" );

LPTSTR lpsz = new TCHAR[theString.GetLength()+1];

_tcscpy(lpsz, theString);

方法三,使用CString::GetBuffer。例如:

CString s(_T("This is a test "));

LPTSTR p = s.GetBuffer();

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

if(p != NULL) *p = _T('\0');

s.ReleaseBuffer();

//使用完后及时释放,以便能使用其它的CString成员函数

CString str = "ABCDEF";

char *pBuf = str,GetBuffer( 0 );

str.ReleaseBuffer();

二、string转char*

string是c++标准库里面其中一个,封装了对字符串的操作

把string转换为char*有3种方法:

1。data(),返回没有”\0“的字符串数组

如:

string str="abc";

char *p=str.data();

2.c_str返回有”\0“的字符串数组

如:string str="gdfd";

char *p=str.c_str();

3 copy

比如

string str="hello";

char p[40];

str.copy(p,5,0); //这里5,代表复制几个字符,0代表复制的位置

*(p+5)='\0'; //要手动加上结束符

cout < < p;

三、字符串string转换为其它数据类型

temp="123456";

1)短整型(int)

i = atoi(temp);

2)长整型(long)

l = atol(temp);

3)浮点(double)

d = atof(temp);

string s; d= atof(s.c_str());

4)BSTR变量

BSTR bstrValue = ::SysAllocString(L"程序员");

...///完成对bstrValue的使用

SysFreeString(bstrValue);

5)CComBSTR变量

CComBSTR类型变量可以直接赋值

CComBSTR bstrVar1("test");

CComBSTR bstrVar2(temp);

6)_bstr_t变量

_bstr_t类型的变量可以直接赋值

_bstr_t bstrVar1("test");

_bstr_t bstrVar2(temp);

四、Char*转换为string

如果要把一个char转换成string,可以使用string s(char *);

五、string转CString

CString.format("%s", string.c_str());

六、char转CStringCString.format("%s", char*);

七、CString -> string

string s(CString.GetBuffer());

GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.

八、CString互转int

将字符转换为整数,可以使用atoi、_atoi64或atol。

而将数字转换为CString变量,可以使用CString的Format函数。如

CString s;

int i = 64;

s.Format("%d", i)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。