C中的扫描集

    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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值