c++中CString,int,float类型转换

5 篇文章 0 订阅

最近被各种类型转换转晕了,必须写下来,下次使用方便。

1、int,float转CString
无论是int还是float转CSring都是容易的,Format函数可以处理。

这里给出百度的解释:Format是CString类的一个成员函数,它通过格式操作使任意类型的数据转换成一个字符串。

function Format(const Format: string; const Args: array of const): string; overload;
格式指令具有以下的形式: “%” [index “:”] [“-“] [width] [“.” prec] type[type]
type参数可选的类型有d,u,f,e,g,n,m,p,s,x.
1) d 十进制数,表示一个整型值,u 和d一样是整型值,但它是无符号的,而如果它对应的值是负的,则返回时是一个2的32次方减去这个负数的绝对值。
2)f 对应浮点数
3)e科学表示法,对应整型数和浮点数
4)g 这个只能对应浮点型,且它会将值中多余的数去掉
5)n 只能对应浮点型,将值转化为号码的形式
例如:Format(“this is %n”,4552.2176);
返回的是:this is 4,552.22
6)m 钱币类型,但关于货币类型有更好的格式化方法,这里只是简单的格式化,另外它只对应于浮点值
例如:Format(“this is %m”,9552.21);
返回的是:this is ¥9,552.21
7)p 对应于指针类型,返回的值是指针的地址,以十六进制的形式来表示
例如:Format(“this is %p”,p);
返回的是:this is 0012F548
8)s 对应字符串类型
9)x 必须是一个整形值,以十六进制的形式返回
例如:Format(“this is %X”,15);
返回的是:this is F

举例:

float temp_latitude=1.235;
CString mt_longitude;
mt_longitude.Format(_T("%f"), temp_longitude);//int型,"%f"改为"%d"即可

2、CString转int

int a;
CString str = (_T("234.98"));
a = _ttoi(str);
str.Format(_T("%d"), a);//最后的结果为234

3、CString转float

#include <stdlib.h>//包含wcstod
float a=12.3546;
CString str;
a = wcstod(str,NULL);//字符串转float
str.Format(_T("%f"), a);//float转字符串

double wcstod (const wchar_t* str, wchar_t** endptr);//Convert wide string to double
另外还有一些其他函数,参照官网说明查看即可:
strtod
Convert string to double (function )
wcstol
Convert wide string to long integer (function )
wcstoul
Convert wide string to unsigned long integer (function )

另外,网上有人写

float a;
CString str;
a = (float)atof((char *)(LPTSTR)(LPCTSTR)str);

我运行了,得到的数字不对。不知道是我哪里出了问题还是怎样

11月28日更新
今天移植程序发现,在之前用10版本写的的程序中用

CString  str=  (_T("234.98"));
a = atof(str);

是可以的,但是我用13建立的工程中,用atof会有如下提示:
错误 6 error C2664: “double atof(const char )”: 无法将参数 1 从“CString”转换为“const char ” c:\users\admin\desktop\程序\chuankou9_end(经纬度海拔)\chuankou9\chuankou9dlg.cpp 340 1 chuankou9

同理,我在10版本的程序中使用atof可以,但是使用wcstod时,会提示“错误 10 error C2664: “double wcstod(const wchar_t ,wchar_t *)”: 无法将参数 1 从“CString”转换为“const wchar_t *” c:\users\admin\desktop\kilometerpost_test\kilometerpost\kilometerpostdlg.cpp 510 1 KilometerPost

这是字符转换的问题。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值