VC編程CString、int、string、char*相互轉換



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");
}



發佈了33 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章