C++ 数字、string 简便互转
2024-08-29 23:01:22
一、数字转为 string 类型
借用 sprintf 函数:
char buffer[256];
int counter = 10;
sprintf(buffer,"%04i", counter);
std::string number = std::string(buffer);
二、string 类型转为数字
C 标准库提供了 atoi, atof, atol, atoll(C++ 11标准)函数将 char* 字符串转换成 int, double, long, long long 型:
char str[] = "15.455";
double db;
int i;
db = atof(str); // db = 15.455
i = atoi(str); // i = 15
若字符串为 string 类型。则要用 c_str() 方法先转化为 char* 字符串。例如以下:
string str = "15.455";
double db;
int i;
db = atof(str.c_str()); // db = 15.455
i = atoi(str.c_str()); // i = 15
最新文章
- jquery使用案例
- Intent跳转传list集合
- thinkphp 调用系统的方法
- lower_bound 和 upper_bound
- 抽屉显示控件SlidingDrawer入门
- maven依赖传递关系
- 用DIV+Css+Jquery 实现的旧版微信飞机大战。
- self和super之间的区别
- testNg官方文档
- c语言实现动态指针数组Dynamic arrays
- mysql 初始化时root无密码
- Ubuntu下关闭防火墙
- TSQL:A表字段与B表中的关联,关联条件中一列是随机关联的实现方式
- SQLServer之修改索引
- springboot情操陶冶-SpringApplication(一)
- Centos 6.x 升级到 7.x
- Linux:ldd命令详解
- oracle体系结构理解
- Druid连接池(三)
- [usaco]2013-jan Liars and Truth Tellers 真假奶牛