1 利用stringstream
添加头文件 #include<sstream>
数字转字符串
#include <string>
#include <sstream>
int main(){
double a = 123.32;
string res;
stringstream ss; 定义流ss
ss << a; 将数字a转化成流ss
ss >> res; 将流ss转化成字符串
return 0;
}
字符串转数字
#include <string>
#include <sstream>
int main(){
double a ;
string res= "123.32";
stringstream ss;
ss << res;
ss >> a;
return 0;
}
//此处包装了一个方法,将一位的数字转化成两位的字符串
//0->"00" 1->''01"
string transform(int num)
{
string res;
stringstream ss;
ss<<num;
ss>>res;
if(num<10)
{
res="0"+res;
}
return res;
}
2.利用 sprintf()函数和sscanf()函数
sprintf() 用于将数字转化为字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[10];
int a=1234321;
//将整数转化为字符串
sprintf(str,"%d",a);
int len=strlen(str);
cout<<"字符串"<<str<<endl;
cout<<"长度"<<len<<endl;
char str1[10];
double b=123.321;
/ /将浮点数转化为字符串
sprintf(str1,"%.3lf",b);
int len1=strlen(str1);
cout<<"字符串"<<str1<<endl;
cout<<"长度"<<len1<<endl;
return 0;
}
sscanf() 用于将字符串转化为数字
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[]="1234321";
int a;
sscanf(str,"%d",&a);
cout<<a<<endl;
char str1[]="123.321";
double b;
sscanf(str1,"%lf",&b);
cout<<b<<endl;
return 0;
}