C++ 数字、string 简便互转

时间:2014-08-29 18:21:58   收藏:0   阅读:174

一、数字转为 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


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!