您的位置:首页 > Web前端

CString,string,char *,int之间的转换

2010-06-10 16:34 295 查看
先弱弱的说下CString,string,char

CString是MFC提供的一个处理字符串的类

string是C++标准库中提供处理字符串的类

char是原生从C来的字符串处理

string 转 CString

CString.format("%s", string.c_str());

char* 转 CString
CString.format("%s", char*);

char* 转 string
string s(char *);
你的只能初始化,在不是初始化的地方最好还是用assign().

 

string 转 char *
char *p = string.c_str();

CString 转 string
string s(CString.GetBuffer());
GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.

 

CString 转 char*

 CString cstr("zctong");
 char *pstr=NULL;
 pstr=cstr.GetBuffer(cstr.GetLength());

CString 转 char*的一些细节点

 CString s( "abcd" );

 #ifdef _DEBUG
  afxDump << "CString s " << s << "/n";
 #endif
  LPTSTR p = s.GetBuffer( 10 );
  strcpy( p, "Hello" );   // directly access CString buffer。
  s.ReleaseBuffer( );
 #ifdef _DEBUG
  afxDump << "CString s " << s << "/n";
 #endif

 

LPTSTR GetBuffer( int nMinBufLength );
throw( CMemoryException );

这个函数放回的是LPTSTR,不是const类型,所以可以使用放回来的指针直接修改CString中的内容

当你使用返回的指针修改CString中的内容后,必须调用ReleaseBuffer后才能调用其他CString成员函数(必须的,不然肯定杯具)

而当你调用ReleaseBuffer后,这前面返回的指针LPTSTR则可能已经无效了

void ReleaseBuffer( int nNewLength = -1 );

The new length of the string in characters, not counting a null terminator. If the string is null-terminated, the -1 default value sets the CString size to the current length of the string.
 

将字符转换为整数,可以使用atoi、_atoi64或atol。
而将数字转换为CString变量,可以使用CString的Format函数。如
CString s;
int i = 64;
s.Format("%d", i)
Format函数的功能很强,值得你研究一下。
void CStrDlg::OnButton1()
{
// TODO: Add your control notification handler code here
CString
ss="1212.12";
int temp=atoi(ss);
CString aa;
aa.Format("%d",temp);
AfxMessageBox("var is " + aa);
}
sart.Format("%s",buf);

 

常用的移位处理
对消息的处理中我们经常需要将WPARAM或LPARAM等32位数据(DWORD)分解成两个16位数
据(WORD),例如:
LPARAM lParam;
WORD loValue = LOWORD(lParam);///取低16位
WORD hiValue = HIWORD(lParam);///取高16位
对于16位的数据(WORD)我们可以用同样的方法分解成高低两个8位数据(BYTE),例如
:
WORD wValue;
BYTE loValue = LOBYTE(wValue);///取低8位
BYTE hiValue = HIBYTE(wValue);///取高8位
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息