CString,string,char*,char a[100],int之间转换

 /*string->CString*/
 /* 
 string str;
 CString cstr;
 str="xiaowen";
 cstr.Format("%s",str.c_str());
 cout<<"str="<<str<<endl;  //输出xiaowen
 cout<<"cstr="<<cstr.GetBuffer (sizeof(CString))<<endl;  //输出xiaowen
 cout<<"cstr="<<cstr.GetBuffer (cstr.GetLength ())<<endl;  //输出xiaowen

 

 /*char*->CString*/
 /*
 char *p="xiaowen";
 CString cstr2;
 cstr2.Format ("%s",p);
 cout<<"p="<<p<<endl;  //输出xiaowen
 cout<<"cstr2="<<cstr2.GetBuffer (sizeof(CString))<<endl;  //输出xiaowen
 */

 

 /*string->const char* */
 /*
 string s2("xiaowen");
 const char *p=s2.c_str ();
 cout<<"p="<<p<<endl;  //输出xiaowen
 cout<<"s2="<<s2<<endl;   //输出xiaowen
 */

 

 /*CString->string*/
 /*
 CString cstr3("xiaowen");
 string str3;
 str3=cstr3.GetBuffer (sizeof(cstr3));
 cout<<"str3="<<str3<<endl;  //输出xiaowe
 cout<<"cstr3="<<cstr3.GetBuffer (sizeof(cstr3))<<endl;  //输出xiaowe
 */

 

 /*char*->string*/
 /*
 char *p="xiaowen";
 string str4(p);
 cout<<"p="<<p<<endl; //输出xiaowe
 cout<<"str4="<<str4<<endl; //输出xiaowe
 string str5;
 str5.assign (p);
 cout<<"str5="<<str5<<endl;  //输出xiaowe
 char *q="xiaowen22";
 str4.assign (q);
 cout<<"str4="<<str4<<endl; //输出xiaowe22
 */

 

 /*CString->char*,CSting->const char* */
 /*
 CString cs("xiaowen");
 const char *p=(LPCSTR)cs;
 cout<<"cs="<<cs.GetBuffer (sizeof(cs))<<endl;  //输出xiaowen
 char *q=cs.GetBuffer (sizeof(cs));
 cout<<"q="<<q<<endl; //输出xiaowen
 */

 

 /*CString->int*/
 /*
 CString cs="1234";
 int i;
 i=atoi(cs.GetBuffer (sizeof(cs)));
 cout<<"i="<<i<<endl;  //输出1234
 */

 

 /*int->CString*/
 /*
 int i=3999;
 CString cs2;
 cs2.Format ("%d",i);
 cout<<"cs2="<<cs2.GetBuffer (sizeof(cs2))<<endl;  输出3999
 */

 

 /*CSting->char [100]*/
 /*
 char a[20];
 CString cs="xiaowen";
 strncpy(a,(LPCSTR)cs,sizeof(a)-1);
 cout<<"a="<<a<<endl;  //输出xiaowen
 */
 注:
 1.CString在头文件<afx.h>中,VC->工程->设置->General->使用MFC作为共享的DLL,否则可能出错

 2.string::c_str():返回C-string形式的字符串,在尾端添加'/0',而string::data()以字符数组形式返回字符串内容,并未追加'/0',copy()将字符串内容复制到“调用者提供的字符数组”中,不添加'/0',注意函数返回值有效期限

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值