scanf系列函数支持由%[]表示的扫描集说明符。在扫描集内部,我们可以指定单个字符或字符范围。在处理扫描集时,scanf将只处理那些属于扫描集的字符。我们可以通过将字符放在方括号内来定义扫描集。请注意,扫描集区分大小写。
我们还可以通过在要添加的字符之间提供逗号来使用扫描集。
示例:scanf(%s[A-Z,_,a,b,c]s,str);
这将扫描扫描集中所有指定的字符。
让我们举个例子看看。下面的示例只将大写字母存储到字符数组“str”中,任何其他字符都不会存储在字符数组中。
/* A simple scanset example */
#include <stdio.h>
int main(void)
{
char str[128];
printf("Enter a string: ");
scanf("%[A-Z]s", str);
printf("You entered: %s\n", str);
return 0;
}
[root@centos-6 C]# ./scan-set
Enter a string: GEEKs_for_geeks
You entered: GEEK
如果扫描集的第一个字符是’^’,那么说明符将在该字符第一次出现后停止读取。例如,下面给出的扫描集将读取所有字符,但在第一次出现“o”后停止。
scanf("%[^o]s", str);
让我们举个例子看看。
/* Another scanset example with ^ */
#include <stdio.h>
int main(void)
{
char str[128];
printf("Enter a string: ");
scanf("%[^o]s", str);
printf("You entered: %s\n", str);
return 0;
}
[root@centos-6 C]# ./scan-set
Enter a string: http://geeks for geeks
You entered: http://geeks f
[root@centos-6 C]#
让我们使用扫描集来实现gets() 函数。get() 函数从标准输入读取一行到 s 指向的缓冲区,直到找到终止的换行符或 EOF。
/* implementation of gets() function using scanset */
#include <stdio.h>
int main(void)
{
char str[128];
printf("Enter a string with spaces: ");
scanf("%[^\n]s", str);
printf("You entered: %s\n", str);
return 0;
}
[root@centos-6 C]# ./gets
Enter a string with spaces: Geeks For Geeks
You entered: Geeks For Geeks
[root@centos-6 C]#
顺便说一句,一般来说,使用gets()可能不是一个好主意。检查以下Linux手册页的注释。
永远不要使用gets()。 因为在事先不知道数据的情况下无法判断gets() 会读取多少个字符,而且gets() 会继续存储超过缓冲区末尾的字符,所以使用起来极其危险。 它已被用来破坏计算机安全。 请改用 fgets()。 也可以看看这个帖子。
参考文档
[1]Narendra Kangralkar.Scansets in C[EB/OL].https://www.geeksforgeeks.org/scansets-in-c/,2020-10-28.