您的位置:首页 > 其它

笔记:MFC中CString和其他类型的转换

2016-07-23 10:37 483 查看
这是我在网上各个地方搜集到的准确可用的类型转换(反正我在VS2013的MFC都可行),现在整理好留作将来参考,也给和我一样到处找转换方法的人一起参考参考。

一:其他类型转换成CString

1、常用类型通过Format函数赋值给CString

例如

1、int转换成CString

int a = 123;

CString str;

str.Format(_T("%d"), a);

可以将数字123存入temp中而非123对应的ASCII字符

2、char[]转换成CString

char a[10]="abcdefgh";

CString str;

str.Format(_T("%s"),a);

3、其他类型一样,更改参数%*即可

2、char*通过A2W(A2T)赋值给CString

把char *赋值给CString

char *enc="adf";

USES_CONVERSION;

CString str=A2W(enc); //或者A2T

二:CSstring转换成其他类型

1、把CString 值赋给分配内存的char *。

CString str="fasdf";

int nSize = str.GetLength() * 2;

int len = WideCharToMultiByte(CP_ACP, 0, str, nSize/2, NULL, 0, NULL, NULL);

char *t=new char[len+1];

WideCharToMultiByte(CP_ACP, 0, str, nSize / 2, t, len, NULL, NULL);

t[len] = '\0';

2、把CString 值赋给未分配内存的char *。

CString str = _T("小黄");

USES_CONVERSION;

char* p = T2A(str.GetBuffer(0));

str.ReleaseBuffer();

3、把CString 值赋给已分配内存的char[]数组.

ASC:

CString str = "ASDDSD";

int strLength1 = str.GetLength() + 1;

char chArray[100];

memset(chArray,0, sizeof(bool) * 100); //将数组用0填充

strncpy(chArray, str, strLength1);  //将str赋值给数组

UNICODE:

CString str="q312";

char q[123];

int nSize = str.GetLength() * 2;
memcpy(q, str, nSize);

4、CString赋值给int类型,直接变为数字

CString str=_T("123");

int temp=_ttoi(str);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cstring mfc visual studio