vc在unicode和非unicode情况下cstring转换为float

CString str = CString(“Almost mad!”);
float tempFloat = 0.0;
tempFloat = atof(str);,

  • 1
  • 2
  • 3

但是出现这样的错误

  error   C2664:   'atof'   :   cannot   convert   parameter   1   from   'CString'   to   'const   char   *'  

  
  
  • 1

原因:

工程是UNICODE, unicode下LPCTSTR可不是const char *

建议 :

CString   str;   
float   fi;   
fi   =   _tstof(str);   

  
  
  • 1
  • 2
  • 3

这样无论是不是unicode下,就都可以了

解决方案:

double   atof(   
        const   char   *str     
  );   
  double   _wtof(   
        const   wchar_t   *str     
  );   

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

atof是非unicode版本的,所以接受参数为const char *。
_wtof才是unicode下的,所以接受宽字符为参数。

为了统一,可以用_tstof或者_ttof。

非Unicode下,直接用GetBuffer(0)得到的就是单字节字符指针。

Unicode下,将GetBuffer(0)得到的宽字符指针用W2A宏转成单字节字符指针。

猜你喜欢

转载自blog.csdn.net/baidu_37503452/article/details/87933445