C++ 数字、string 简便互转

  • Post author:
  • Post category:其他



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



版权声明:本文为yOung_One原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。