sscanf函数
sscanf的作用:从一个字符串中读进于指定格式相符的数据。利用它可以从字符串中取出整数、浮点数和字符串。
sscanf和scanf的区别:scanf是以键盘作为输入源,sscanf是以字符串作为输入源。
注意:如果第一个字符匹配失败就会结束匹配,所以需要适当过滤操作
注意:如果开头是空格或\n等字符,会直接跳过这些空白字符
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICMyYTMvw1dvwlMvwlM3VWaWV2Zh1Wa-cmbw5CaxcWa3YmMuJjcvw1NyQTM3IDOtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
提取某个字符串中的有效信息,放入指定变量或字符串中
跟scanf一样,遇到空格或者换行结束读取
如果是拆分后放入多个字符串中,会首先看第一个字符是否匹配成功,如果不成功结束匹配,然后拆分过程中遇到空格结束拆分当前字符串,将所读取的内容放入指定字符串中,然后查看后续是否还有要放入的字符串,如果有继续进行下一轮拆分,直到没有要放入的子符串为止
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
void test()
{
//sscanf函数
char s[200]="拨不通的电话, 遍布星辰的晚上, 拨不通的电话, 信号丢失云层上";
char s1[300] = {0};
char s2[300] = {0};
char s3[300] = {0};
char s4[300] = {0};
//遇到空格结束读取
sscanf(s, "%s %s %s %s", s1,s2,s3,s4);
printf("%s", s1);
printf("%s", s2);
printf("%s", s3);
printf("%s", s4);
}
int main()
{
test();
return 0;
}
复制
将已知的字符串通过格式化匹配出有效信息
1、%*s或%*d 跳过数据,%*2d可以选择跳过几个数字,不然就会默认都跳过
2、%[width]s 读指定宽度的数据
3、%[a-z] 匹配a到z中任意字符(尽可能多的匹配)
4、%[aBc] 匹配a、B、c中一员,贪婪性
5、%[^a] 匹配非a的任意字符,贪婪性
6、%[^a-z] 表示读取除a-z以外的所有字符
1.取出指定长度字符串
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("12345","%4s",str);
printf("%s\n",str);
return 0;
}
复制
2.格式化时间
#include<stdio.h>
#include<string.h>
int main()
{
int year, month, day, hour, minute, second;
sscanf("2013/02/13 14:55:34","%d/%d/%d %d:%d:%d",&year, &month, &day, &hour, &minute, &second);
printf("time=%d-%d-%d %d:%d:%d\n", year, month, day, hour, minute, second);
char buf1[64] = {0};
int year;
int month;
int day;
char ch[32] = { 0 };
char ch1[32] = { 0 };
char ch2[32] = { 0 };
sscanf("2002/2/18 hello the world", "%d/%d/%d %s %s %s",&year,&month,&day,&ch,&ch1,&ch2);
printf("%d/%d/%d %s %s %s",year,month,day,ch,ch1,ch2);
return 0;
}
复制
3.读入字符串
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("12345","%s",str);
printf("%s\n",str);
return 0;
}
复制
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("1234abcd","%*d%s",str);
printf("%s\n",str);
return 0;
}
复制
5.字符串中未输入数据
注意:如果[]或者[^]里面不填需要的字符,那么便不会向子符串中输入任何数据
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("1234+abc1234","%[^]",str);
printf("str=%s\n",str);
//
char str[100] = {0};
sscanf("1234+abc1234", "%[]", str);
printf("str=%s", str);
return 0;
}
复制
6.取到指定字符集为止的字符串。如遇到小写字母为止的字符串。
注意:如果第一个字符就是a~z里面的字母,便直接结束当前字符串拆分,没有向str中写入数据
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("1234+abc1234","%[^a-z]",str);
printf("%s\n",str);
return 0;
}
复制
7.取仅包含指定字符集的字符串。(取仅包含数字和小写字母的字符串,是取得连续的字符串)。
注意:如果第一个字符不是集合1-9和集合a-z,那么匹配失败,str中未输入数据
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("123456abcdefBFRGTY7890","%[1-9a-z]",str);
printf("%s\n",str);
return 0;
}
复制