scanf系列函数支持扫描集说明符,这些说明符由%[]表示。在扫描集中,我们可以指定单个字符或字符范围。在处理扫描集时,scanf将只处理扫描集中的字符。我们可以通过将字符放在方括号内来定义扫描集。请注意,扫描集区分大小写。
null
我们还可以通过在要添加的字符之间提供逗号来使用扫描集。
例如:扫描频率(%s[A-Z,Z,A,b,c]s,str);
这将扫描扫描集中的所有指定字符。 让我们举个例子看看。下面的示例将只存储字符数组“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" , str); return 0; } |
[root@centos-6 C]# ./scan-set Enter a string: GEEKs_for_geeks You entered: GEEK
如果扫描集的第一个字符是“^”,那么说明符将在该字符首次出现后停止读取。例如,下面给出的扫描集将读取所有字符,但在第一次出现“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" , 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]#
让我们使用扫描集实现get()函数。函数的作用是:将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 ( "%[^]s" , str); printf ( "You entered: %s" , 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]#
顺便说一句,一般来说,使用get()可能不是一个好主意。查看Linux手册页下面的注释。 永远不要使用get()。由于无法在不事先知道数据的情况下判断gets()将读取多少个字符,并且由于gets()将继续存储超过缓冲区末尾的字符,因此使用gets()非常危险。它被用来破坏计算机安全。改用fgets()。 也看到 这 邮递 本文由“Narendra Kangralkar”编辑,Geeksforgeks团队审阅。如果您发现任何不正确的地方,请发表评论,或者您想分享有关上述主题的更多信息。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END