最近用CFile读写文件的时候,遇到一个问题,要将数据由CString 转换为 double类型。
在网上搜到一些结果,基本思想都是这样的:
CString str;
double temp;
int strLength = str.GetLength();
//Convert CString to double type
temp = atof((char *)str.GetBuffer( strLength+ 1));
str.ReleaseBuffer();
即使用MFC中提供的atof。
但是用上面的代码进行转换以后,运行结果总是不对。如取出的CString 是:156.2210,则得到的temp就为:1.0000。
经过分析以后,才明白,在str.GetBuffer( strLength+ 1)时,返回的是一个指向第一个字符的指针,由此得到的转换后的数当然就不对了。正确的写法是:
CString str;
double temp;
char *ch;
int strLength = str.GetLength();
int commaIndex = str.Find('.');
ch = (char *)str.GetBuffer( strLength+ 1);
//define a char array
char chTemp[100];
//initialize
for(int i = 0; i < 100; i++)
{
chTemp[i] = '0';
}
//store char into the char array
for(int i = 0; i < strLength; i++)
{
chTemp[i] = *ch;
ch += 2;
}
//if it's a int, add commar
if (commaIndex < 0)
chTemp[strLength]= '.';
//Convert CString to double type
temp = (float) atof((char *)chTemp);
str.ReleaseBuffer();
经测试,转换后得到的数据正确了。