一、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);
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐