(转载)字符串和数字相互转换
作者:互联网
本文转载自https://www.cnblogs.com/houchen/p/8984164.html
一、利用 sprintf()函数和sscanf()函数
(1)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; }
(2)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; }
标签:include,转换,int,sprintf,str,字符串,sscanf,转载 来源: https://www.cnblogs.com/wenhao-Web/p/12167128.html