您的位置:首页 > 编程语言

VC编程CString、int、string、char*相互转换

2014-05-01 18:03 411 查看

http://vcsos.com/Article/pageSource/120212/20120212013238.shtml

简单总结一下就是:

一:CString:头文件afx.h,字符指针转成它用Format函数,它转成常量字符指针直接转,用LPCSTR或const char*。它转成非常量指针要用GetBuffer(),用完要用releaseBuffer()。

GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能

二:string:C++的类。字符指针转成它直接初始化,它只能转成常量字符指针,用c_str()。

三:int:它转成char*用itoa(),反过来转化用atoi(),对应宽字符:_itow(),_wtoi();兼容模式:_itot(),_ttoi()。

代码示例:

#include<iostream>
using namespace std;
#include<afx.h>
int main()
{
char *pstr="123456";
const char *pcstr;

string str(pstr);
cout<<"pstr="<<str.c_str()<<endl;

pcstr=str.c_str();
cout<<"pcstr="<<pcstr<<endl;

CString MFCStr;
MFCStr.Format(_T("%s"),pstr);
cout<<"MFCStr="<<(LPCSTR)MFCStr<<endl;

pstr=MFCStr.GetBuffer();
cout<<"pcstr="<<pcstr<<endl;
MFCStr.ReleaseBuffer();

int n;
n=_ttoi(pstr);
cout<<"n="<<n<<endl;

char *pstr2=new char(10);
_itot(n,pstr2,10);
cout<<"pstr2="<<pstr2<<endl;

system("pause");
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: