先講解 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