scanf函数(QUOT;%[^ \\ n]的S"一个)与获得(一) [英] scanf("%[^\n]s",a) vs gets(a)

查看:319
本文介绍了scanf函数(QUOT;%[^ \\ n]的S"一个)与获得(一)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已被告知,当用户输入一个字符串scanf的不应使用。相反,去得到()被大多数专家还对计算器的用户。我从来没有问它为什么计算器不应该使用在scanf函数的字符串得到。这不是实际的问题,但这个问题的答案是大大AP preciated。

I have been told that scanf should not be used when user inputs a string. Instead, go for gets() by most of the experts and also the users on StackOverflow. I never asked it on StackOverflow why one should not use scanf over gets for strings. This is not the actual question but answer to this question is greatly appreciated.

现在来的实际问题。

scanf("%[^\n]s",a); 

这读取字符,直到用户输入一个新的行字符,考虑到空格也作为字符串。

This reads a string until user inputs a new line character, considering the white spaces also as string.

有没有问题,如果我用

scanf("%[^\n]s",a);

而不是得到?

时被超过scanf函数的功能优化,因为它的声音,得到的是纯粹专用于处理字符串。请让我知道这件事。

Is gets more optimized than scanf function as it sounds, gets is purely dedicated to handle strings. Please let me know about this.

更新

链接帮助我更好地理解它。

This link helped me to understand it better.

推荐答案

得到(3)是危险的,应该不惜一切代价避免。我不能想象一个使用其中得到(3)是的的一个安全漏洞。

gets(3) is dangerous and should be avoided at all costs. I cannot envision a use where gets(3) is not a security flaw.

scanf函数(3)%S 也是危险的 - 你必须使用字段宽度说明以表明您已经分配的缓冲区的大小。如果没有字段宽度,这个程序是一样危险得到(3)

scanf(3)'s %s is also dangerous -- you must use the "field width" specifier to indicate the size of the buffer you have allocated. Without the field width, this routine is as dangerous as gets(3):

char name[64];
scanf("%64s", name);

GNU C库提供了 A 修改%S 的分配缓冲区为您服务。这种非移植的扩展可能较少,难以正确使用:

The GNU C library provides the a modifier to %s that allocates the buffer for you. This non-portable extension is probably less difficult to use correctly:

   The GNU C library supports a nonstandard extension that
   causes the library to dynamically allocate a string of
   sufficient size for input strings for the %s and %a[range]
   conversion specifiers.  To make use of this feature, specify
   a as a length modifier (thus %as or %a[range]).  The caller
   must free(3) the returned string, as in the following
   example:

       char *p;
       int n;

       errno = 0;
       n = scanf("%a[a-z]", &p);
       if (n == 1) {
           printf("read: %s\n", p);
           free(p);
       } else if (errno != 0) {
           perror("scanf");
       } else {
           fprintf(stderr, "No matching characters\n"):
       }

   As shown in the above example, it is only necessary to call
   free(3) if the scanf() call successfully read a string.

这篇关于scanf函数(QUOT;%[^ \\ n]的S"一个)与获得(一)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆