一、int/long/float/double 轉 字符串
方法1:itoa, ltoa(a表示array數組的意思)
頭文件:stdlib.h
示例:
int a = 3;
long b = 23;
char buf1[30] = "";
itoa(a, buf1, 10);//10表示十進制,buf1保存的內容為"3"
char buf2[30] = "";
ltoa(b, buf2, 10);//10表示十進制,buf2保存的內容為"32"
方法2:sprintf
頭文件:stdio.h
示例:
int a = 3;
float b = 4.2f;
char buf[30] = "";
sprintf(buf, "%d,%f", a, b);//buf保存的內容為"3,4.2",可對比printf
方法3:ostringstream
頭文件:#include <sstream>
using namespace std;
示例:
int a = 3;
float b = 4.2f;
ostringstream s1;
s1<<a<<","<<b;//可對比cout
string s2 = s1.str();//s2保存的內容為"3,4.2"
二、字符串 轉 int/long/float/double
方法1:atoi,atol,atof
頭文件:stdlib.h
示例:
int a = atoi("32");
long b = atol("333");
double c = atof("23.4");
方法2:strtol, strtod
頭文件:stdlib.h
示例:
long b = strtol("333", NULL, 10);//10表示十進制
double c = strtod("32.3", NULL);
方法3:sscanf
頭文件:stdio.h
示例:
int a;
float b;
sscanf("23 23.4", "%d %f", &a, &b);//對比scanf
方法4:istringstream
頭文件:#include <sstream>
using namespace std;
示例:
int a;
float b;
istringstream s1("23 23.4");
s1>>a>>b;//對比cin
摘自 Justme0的專欄