组包:按照需要的格式组成字符串
解包:解析特定格式的数据
网络信息传输解析字符串的格式使用较多!
1、sprintf用于组包
将零散的数据格式按照固定的格式组成字符串
#include <stdio.h>
int sprintf(char *str, const char *format, ...);
// format是按照特定的格式
// str是字符数组的起始地址

使用sprintf将数字转化为字符串
void test1()
{
char buff[128] = {0};
// 将数字127转化为字符串127,并保存在字符数组中
sprintf(buff, "%d", 127);
printf("字符串 :%s\n", buff);
}
int main(int argc, char const *argv[])
{
test1();
return 0;
}
2、sscanf用于解包
%d 提取 '0' ~ '9'

%s提取字符串,遇到 '\0' 空格 回车 就会结束

3、sscanf的高级用法
(1)、跳过几个数据 %*d %*s
空格容易被编译器优化

但是其余符号不会被优化

(2)、读取指定宽度的数据 %[width]s %[width]d

(3)、请将字符串 "12345678"中的 34 用整数提取,67用字符串提取
void test3()
{
char str[128] = {'\0'}; // 67
int num = 0; // 34
//从前往后提取,流指针依次往后移动提取
sscanf("12345678", "%*2d%2d%*1c%2s", &num, str);
printf("num = %d,str = %s\n", num, str);
}
int main(int argc, char const *argv[])
{
test3();
return 0;
}

