//亲测可行,欢迎指正补充
//测试环境 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.youkuaiyun.com/topics/220013347
http://bbs.youkuaiyun.com/topics/60316277
http://greatverve.cnblogs.com/archive/2012/10/24/cpp-int-string.html
http://blog.youkuaiyun.com/yysdsyl/article/details/2463662