sprintf()是把格式化数据输出成(存储到)字符串。
sscanf()是从字符串中读取格式化的数据。
下面用个例子来说明:
先定义一个结构体
struct S
{
int age;
float f;
char arr[10];
};
运用sprintf()函数
int main()
{
struct S s = { 10, 5.236f, "abcdefg" };
char buf[100] = { 0 };
//将格式化的数据转换成字符串存储到buf中
sprintf(buf, "%d %f %s\n", s.age, s.f, s.arr);
//输出buf
printf("%s\n", buf);
return 0;
}
运用sscanf()函数
int main()
{
struct S s = { 10, 5.236f, "abcdefg" };
struct S temp = { 0 };
char buf[100] = { 0 };
//将格式化的数据转换成字符串存储到buf中
sprintf(buf, "%d %f %s\n", s.age, s.f, s.arr);
//输出buf
//printf("%s\n", buf);
//从buf中读取格式化的数据到temp中
sscanf(buf, "%d %f %s\n", &(temp.age), &(temp.f), temp.arr);
//输出temp
printf("%d %f %s\n", temp.age, temp.f, temp.arr);
return 0;
}