【C++】int转char*、char*转int、float转char*、char*转float方法汇总及踩坑指南

一、int转char*
如题,本人一开始的思路是先将int值转换为string类型,然后再通过内置的函数c_str()来转成const char*。
本人的代码如下:

int temp = 10;
const char* temp_char = std::to_string(temp).c_str();

但是如果这么写的话,打印结果是空的。
本人的猜想是转成string的时候还没开辟一个专属于这个string类的内存空间以及对应的指针,所以调用c_str()自然是没有结果的。
本人针对上述的猜想了,做了小改动后,结果就正确了,代码如下:

int temp = 10;
string temp_str = std::to_string(temp);
const char* temp_char = temp_str.c_str();

当然,可以一开始就不用先转string再转char*,可以直接转
方法1:

int temp = 10;
char temp_char[10];
_itoa(temp , temp_char, 10); 

方法2:

int temp = 10; 
char temp_char[10];  
sprintf(temp_char,"%d",temp);  

参考资料:
c++ int转char*

二、char*转int
方法1:

char temp_char[] = "200";
int temp_int = atoi(temp_char);

三、float转char*
(float转char*貌似没有_ftoa函数)
方法1:

float temp = 123.456789; 
char temp_char[10];  
sprintf(temp_char,"%f",temp);  

Tip:
使用上述代码时需要在预处理定义中添加_CRT_SECURE_NO_WARNINGS
参考资料:
使用sprintf格式化字符串出错:error C4996: ‘sprintf’: This function or variable may be unsafe.

四、char*转float
方法1:

char temp_char[] = "200.4444";
float temp_int = atof(temp_char);
  • 15
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值