sscanf的作用:从一个字符串中读进于指定格式相符的数据。利用它可以从字符串中取出整数、浮点数和字符串。 sscanf和scanf的区别:scanf是以键盘作为输入源,sscanf是以字符串作为输入源。

提取某个字符串中的有效信息,放入指定变量或字符串中 跟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.取到指定字符集为止的字符串。如遇到小写字母为止的字符串。
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("1234+abc1234","%[^a-z]",str);
printf("%s\n",str);
return 0;
}
7.取仅包含指定字符集的字符串。(取仅包含数字和小写字母的字符串,是取得连续的字符串)。
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
sscanf("123456abcdefBFRGTY7890","%[1-9a-z]",str);
printf("%s\n",str);
return 0;
}