先讲解 sscanf 和 sprintf 的作用:
sscanf(a,"%lf",&temp)
:从 a(字符串)中读进与指定格式相符的数据输入到 temp 中
sprintf(b,"%.2f",temp)
:将 temp 格式化输入到 b(字符串)中 (注意没有&号)
下面以部分本代码举例:
char a[50], b[50];
double temp;
scanf("%s", a);
sscanf(a, "%lf", &temp);
sprintf(b, "%.2f",temp);
cout<<temp<<' '<<b;
//从下列实例看出排除了多种不合法数据
input:1.23.4
ouput:1.23 1.23
input:45.678
ouput:45.678 45.68
input:aaa
ouput:4.94066e-324 0.00
以其他例子举例:
char str[100]="1234:3.14,hello",arr[10];
int n;
double db;
sscanf(str,"%d:%lf,%s",&n,&db,arr); //注意这里不能用 %.2lf(似乎是规定)
cout<<n<<' '<<db<<' '<<arr<<endl;
char str2[100],arr2[]="hello";
int n2=1234;
double db2=3.14;
sprintf(str2,"%d:%.2lf,%s",n2,db2,arr2);
cout<<str2;
//下面实例说明此函数可以转换多个参数
output:
1234 3.14 hello
1234:3.14,hello