C++|std::string和char与uint_32t、double、int等相互转换

std::string转换为uint32_t or int
string不能直接转int需要先转为char*

std::string str = "12";
uint32_t val = std::atoi(str.c_str());
int val = std::atoi(str.c_str());

char 转为int

char str[10]="121";
int num=atoi(str);

int 转为char
需要头文件#include<stdlib.h>
如果itoa报错则需要在项目预处理器中加入_CRT_NONSTDC_NO_DEPRECATE和_CRT_SECURE_NO_WARNINGS。
详见:
itoa报错解决方法
https://blog.csdn.net/hou09tian/article/details/80616155

int num = 10;
char a[3];
itoa(num, a, 10);	// 最后一位为进制数此处是10进制

std::string or char转double or float

std::string str = "12.32";
double val = std::atof(str.c_str());
float val = std::atof(str.c_str());

int or double转为 std::string

int a = 10;
std::string b = std::to_string(a);

double a = 12.22;
std::string b = std::to_string(a);

double转为char
需要头文件#include < sstream >

double d = 12.4500;
std::ostringstream oss1;
oss1 << d;

char fileName[50];
memset(fileName, 0, 50);

//先转化为流,再转换为string, 然后再转换为char
strcat(fileName, (oss1.str()).c_str());
for (int i = 0; i < strlen(fileName); ++i){
	std::cout << fileName[i];
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇树谦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值