CString,string,char[],int相互之间的转换

//亲测可行,欢迎指正补充

//测试环境 vs2008
{
 CString cstrText;
 string strText;
 char* charText;
 int intText;
 float floatText;

 //CString->string
 cstrText="abcd";
 strText="";
 //方法1
 strText=LPCSTR(cstrText);
 //方法2
 strText=cstrText.GetBuffer(0);
 cstrText.ReleaseBuffer();
 //GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.

 //string->CString
 strText="abcd";
 cstrText="";
 //方法一
 cstrText=strText.c_str();
 //方法二
 cstrText=strText.data();
 //方法三
 cstrText.Format("%s",strText.c_str());
 //方法四
 cstrText.Format("%s",strText.data());
 /*c_str()和data()区别是:前者返回带'\0'的字符串,后者则返回不带'\0'的字符串*/

 //string->char[]
 strText="abcd";
 charText=new char[strText.length()+1];
 strText.copy(charText,strText.length(),0);
 charText[strText.length()]='\0';
 delete[] charText;
 charText=NULL;
 //注意,c_str()返回的也是char*,如果只是传参需要,可直接用cstr()

 //char[]->string
 char pText[]="abcd";  //自动添加'\0'
 strText=pText;  //或初始化时直接赋值 string strText(pText);
 
 //int,float->CString
 intText=1;
 floatText=1.2;
 cstrText.Format("%d",intText);
 cstrText.Format("%f",floatText);

 //Cstring->int,float;
 cstrText="123";
 intText=atoi(cstrText);
 cstrText="12.3";
 floatText=atof(cstrText);
 //相应的函数有atoi,atol,strtod,strtol,strtoul

  //int,float->string
  intText=123;
 itoa(intText,(char*)(strText.c_str()),10);    //vc6编译会出错

 //string->int,float
 strText="1234";
 intText=atoi(strText.c_str());
 strText="123.4";
 floatText=atof(strText.c_str());
 //相应的函数有atoi,atol,strtod,strtol,strtoul
}

参考资料:
http://www.cnblogs.com/ziwuge/archive/2011/06/19/2084608.html
http://bbs.csdn.net/topics/220013347
http://bbs.csdn.net/topics/60316277
http://greatverve.cnblogs.com/archive/2012/10/24/cpp-int-string.html
http://blog.csdn.net/yysdsyl/article/details/2463662

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值