您的位置:首页 > 其它

VC下CString类型与int 、float等数据类型的相互转换

2014-03-13 20:54 597 查看
一、常用转换

1. CString --> int转换

CString str("1234");

int i= _ttoi(str);

2. CString --> float转换

方法一:

CString str;

float fi;

fi=_tstof(str); //转成了double

方法二:

float i = (float)atof(str.GetBuffer(str.GetLength()));

方法三:

 float f = atof((LPCSTR)str);

3. int --> CString 转换

wScale = 300 * _tstof(dlg.GetRate());

str.Format(_T("%d"), wScale);

4. float --> CString 转换

float m_Result = 99.9;

CString m_ShowData.Format("%f", m_Result);

二、将CString转换为double(或float)的3种方法

CString strFloat;

float flt;

//method1:

flt = (float)atof((char *)(LPTSTR)(LPCTSTR)mstrFloat);

//method2:

flt = (float)atof((char *)m_eps.GetBuffer(strFloat.GetLength()));

strFloat.ReleaseBuffer();

//method3:

//Convert CString to double

static BOOL _AtlSimpleFloatParse(LPCTSTR lpszText, double& d)

{

ATLASSERT(lpszText != NULL);

while (*lpszText == ' '|| *lpszText == '/t')

{

lpszText++;

}

TCHAR chFirst = lpszText[0];

d = _tcstod(lpszText,(LPTSTR*)&lpszText);

if (d == 0.0 && chFirst != '0')

{

return FALSE; //could not convert

}

while (*lpszText == ' '|| *lpszText == '/t')

{

lpszText++;

}

if (*lpszText != '/0')

{

return FALSE; //not terminated properly

}

return TRUE;

}

不过前面两种方法在VS2005下运行结果不正确,在VC6.0开发环境下是可以的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐