知识点1【sprintf组包】
案例:
int sprintf(buf,"格式",数据)
//buf:用来存放组好的报文
//"格式":按照格式组包
//数据:各个零散的数据
返回值:返回值的是组好的报文的实际长度(不包含'\0')
void test06()
{
int year = 2020;
int mon = 2;
int day = 24;
int len = 0;
//需求:将2020 2 24组成一个"2020年2月24日"
char buf[128]="";
//%d 和 year 类型要一一对应
len = sprintf(buf,"%d年%d月%d日", year,mon,day);
printf("len = %d\n", len);
printf("buf=%s\n",buf);
}
运行结果:
案例:
void test07()
{
char name[]="梁何";
int age = 18;
char sex[]="男";
char addr[]="重庆市潼南区";
char buf[128]="";
int len = 0;
len = sprintf(buf,"姓名:%s 年龄:%d 性别:%s 地址:%s",name,age,sex, addr);
printf("len = %d\n",len);
printf("buf=%s\n",buf);
}
运行结果:
将数值转成字符串:
void test08()
{
int num = 2020;
char buf[128]="";
sprintf(buf,"%d",num);
printf("buf=%s\n", buf);//"2020"
}
知识点2【sscanf解包】
案例1:sscanf的基本语法
void test09()
{
char buf[]="2020年2月24日";
int year=0;
int mon=0;
int day=0;
char ch = 0;
char str_year[32]="";
char str_mon[32]="";
char str_day[32]="";
//%d 只能提取'0'~'9'
sscanf(buf,"%d年%d月%d日", &year,&mon,&day );
printf("year = %d\n",year);//2020
printf("mon = %d\n",mon);//2
printf("day = %d\n",day);//24
//%c 提取一个字符 %f 提取提取浮点数
sscanf(buf,"%c", &ch);
printf("##%c##\n",ch);//'2'
//%s 提取一个字符串 遇到空格、回车、'\0' 停止获取
//buf==>"2020年2月24日"
sscanf(buf,"%s年%s月%s日",str_year, str_mon,str_day );
printf("str_year=%s\n",str_year);//"2020年2月24日"
printf("str_mon=%s\n",str_mon);//null
printf("str_day=%s\n",str_day);//null
}
运行结果:
sscanf的高级用法1:使用%*s %*d 跳过提取的内容(不要提取的内容)
void test10()
{
int data1=0;
//sscanf("1234 5678","1234 %d",&data1);//5678
//sscanf("1234 5678","%*d %d",&data1);//5678
sscanf("1234 5678","%*s %d",&data1);//5678
printf("data1=%d\n",data1);
}
sscanf的高级用法2:使用%[n]s %[n]d 提取指定宽度n的字符串或数据
void test11()
{
int data1 = 0;
int data2 = 0;
char buf[16]="";
sscanf("12abc5678","%*5s%d" ,&data1);//5678
printf("data1=%d\n",data1);
sscanf("12345678","%*2s%2d%*2d%s" ,&data2, buf);//data2=34 buf="78";
printf("data2 = %d\n",data2);//34
printf("buf=%s\n", buf);//"78"
}
运行结果:
知识点3【sscanf高级用法】
1、%[a-z] 提取a-z的字符串
void test01()
{
char buf[128]="";
//%[]都是 按 字符串 提取
sscanf("abcDefABC","%[a-z]",buf);
printf("buf=%s\n", buf);//"abc"
return;
}
2、%[aBc] 提取 a B c
void test02()
{
char buf[128]="";
sscanf("aaBBcEdef","%[aBc]",buf);
printf("buf=%s\n", buf);//aaBBc
}
3、%[^abc] 只要不是a b c任何一个 都要
void test03()
{
char buf[128]="";
sscanf("ABCcABC","%[^abc]",buf);
printf("buf=%s\n", buf);//ABC
}
案例:
void test04()
{
char name[32]="";
char addr[32]="";
//sscanf("lianghe@1000phone.com","%[^@]%*1s%[^.]",name,addr );
//sscanf("lianghe@1000phone.com","%[^@]%*c%[^.]",name,addr );
sscanf("lianghe@1000phone.com","%[^@]@%[^.]",name,addr );
printf("name=%s\n",name);//"lianghe"
printf("addr=%s\n",addr);//"1000phone"
}
案例:
void test05()
{
int m1=0,s1=0;
int m2=0,s2=0;
char song[128]="";
char msg[128]="[12:13.46][8:23.45]给我一个威武雄壮的汉子";
sscanf(msg,"[%d:%d%.%*d][%d:%d.%*d]%s",&m1,&s1,&m2,&s2,song);
printf("%d-%d\n",m1,s1);
printf("%d-%d\n",m2,s2);
printf("%s\n", song);
}
运行结果: