吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C中的scanf系列

C中的scanf系列

来源:网络 | 更新时间:2022-01-08 16:01:08
scanf 系列函数支持由 %[] 表示的扫描集说明符。在扫描集中,我们可以指定单个字符或字符范围。在处理 scanset 时,scanf 将仅处理属于 scanset 的那些字符。我们可以通过将字符放在方括号内来定义扫描集。请注意,扫描集区分大小写。 我们还可以通过在要添加的字符之间提供逗号来使用 scanset。 例如:scanf(%s[AZ,_,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: %sn", str);

return 0;
}
 [root@centos-6 C]# ./scan-set 
  Enter a string: CXYdh_for_52cxydh
  You entered: CXY
如果 scanset 的第一个字符是 '^',则说明符将在该字符第一次出现后停止读取。例如,下面给出的扫描集将读取所有字符,但在第一次出现 '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: %sn", str);

return 0;
}
 [root@centos-6 C]# ./scan-set 
  Enter a string: http://52cxydh for 52cxydh
  You entered: http://52cxydh f
  [root@centos-6 C]#
让我们使用 scan 系列来实现gets()函数。gets() 函数从标准输入读取一行到 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: %sn", str);

return 0;
}
附带说明一下,通常使用 gets() 可能不是一个好主意。从 Linux 手册页查看以下注释。 永远不要使用gets()。因为在事先不知道数据的情况下不可能知道gets()会读取多少个字符,而且因为gets()会继续存储超过缓冲区末尾的字符,所以使用起来非常危险。它已被用来破坏计算机安全。请改用 fgets()。  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com