C语言中的scanset是什么?如何使用?

2021年3月19日13:05:42 发表评论 1,354 次浏览

本文概述

scanf系列函数支持用%[]表示的scanset说明符。在scanset内部, 我们可以指定单个字符或字符范围。在处理scanset时, scanf将仅处理属于scanset的那些字符。我们可以通过将字符放在方括号内来定义scanset。请注意, scanset区分大小写。

我们还可以通过在要添加的字符之间提供逗号来使用scanset。

例如:scanf(%s [A-Z, _, a, b, c] s, str);

这将扫描scanset中的所有指定字符。

让我们来看一个例子。下面的示例仅将大写字母存储在字符数组" str"中, 其他任何字符均不存储在字符数组中。

C

/* 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: lsbin_for_lsbin
  You entered: GEEK

如果scanset的第一个字符为" ^", 则说明符将在该字符首次出现后停止读取。例如, 下面给出的scanset将读取所有字符, 但在首次出现" o"后停止

C

scanf ( "%[^o]s" , str);

让我们来看一个例子。

C

/* 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://lsbin for lsbin
  You entered: http://lsbin f
  [root@centos-6 C]#

让我们通过使用scanset来实现gets()函数。 gets()函数从stdin读取一行到s所指向的缓冲区, 直到找到终止的换行符或EOF。

C

/* 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: lsbin For lsbin
  You entered: lsbin For lsbin
  [root@centos-6 C]#

附带说明一下, 通常使用gets()可能不是一个好主意。在Linux手册页中检查以下注释。

永远不要使用gets()。因为无法不事先知道数据就无法分辨出将读取多少个字符, 并且因为gets()将继续存储缓冲区结束后的字符, 所以使用它非常危险。它已被用来破坏计算机安全性。请改用fgets()。

另见

这个

发布。

本文由" Narendra Kangralkar"编辑, 并由lsbin团队审阅。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: