举例:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char str[100] = {'-', '1', '2', '.', '3', '4', '5'};
char s[100];
int a;
sscanf (str, "%5d", &a);
sprintf (s, "%10d", a);
printf ("%s", s);
return 0;
}
先使用sscanf
从str
中读取宽度为5的整数,再使用sprintf
将整数a
以宽度为10的字符串形式保存在变量s
中。
最后s
中的数据为七个空格与-12
。
#include<bits/stdc++.h>
using namespace std;
int main()
{
char str[100] = {'-', '1', '2', '.', '3', '4', '5'};
char s[100];
double a;
sscanf (str, "%5lf", &a);
sprintf (s, "%.2lf", a);
printf ("%s", s);
return 0;
}
先使用sscanf
从str
中读取宽度为5的浮点数,再使用sprintf
将浮点数a
四舍五入到小数点后两位后以字符串的形式保存在变量s
中。
最后s
中的数据为-12.30
。