CString类型 转换为 double类型

    最近用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();

    经测试,转换后得到的数据正确了。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值