C++ 数字、string 简便互转

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


原文地址:https://www.cnblogs.com/gccbuaa/p/6927794.html