一.概要
sprintf
与printf
作用基本相同都是格式化输出,只不过原始printf
输出的位置是屏幕
,sprintf
输出的位置是字符串
。
二.示例
#include <stdio.h>
#define SIZE 10
int main(void) {
char firstName[SIZE];
char lastName[SIZE];
char formatl[SIZE * 2 + 10];
double prize;
puts("请输入你的名字:");
gets(firstName);
puts("请输入你的姓氏:");
gets(lastName);
puts("请输入你的奖金:");
scanf("%lf", &prize);
sprintf(formatl, "%s,%-10s:$%6.2f\n", lastName, firstName, prize);
puts(formatl);
return 0;
}
输出结果:
请输入你的名字:
jane
请输入你的姓氏:
Vic
请输入你的奖金:
2121.1231
Vic,jane :$2121.12
注:如果格式化输出的内容长度,大于接收数据的数组长度时,sprintf将放弃写入数据,并产生错误信息:"trace trap 。"