c - scanf ("%[^\n]s",a) 与 gets(a)

标签 c scanf gets

有人告诉我当用户输入字符串时不应使用 scanf。相反,大多数专家和 StackOverflow 上的用户都使用 gets() 。我从来没有在 StackOverflow 上问过为什么不应该对字符串使用 scanf 而不是 gets。这不是实际问题,但非常感谢您回答这个问题。

现在进入实际问题。我遇到过这种类型的代码 -

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

这会读取一个字符串,直到用户输入一个换行符,将空格也视为字符串。

使用有问题吗

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

而不是获取?

gets 比 scanf 函数听起来更优化,gets 纯粹专用于处理字符串。请让我知道这件事。

更新

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

最佳答案

gets(3) 是危险的,应该不惜一切代价避免。我无法想象 gets(3) 不是安全漏洞的用途。

scanf(3)%s 也很危险——您必须使用“字段宽度”说明符来指示您分配的缓冲区的大小。没有字段宽度,此例程与 gets(3) 一样危险:

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

GNU C 库为 %s 提供了 a 修饰符 来为您分配缓冲区。这个不可移植的扩展可能更容易正确使用:

   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.

关于c - scanf ("%[^\n]s",a) 与 gets(a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8177752/

相关文章:

c - ANTLR 3.4(C 运行时)中的 antlr3NewAsciiStringCopyStream 发生了什么?

c - C 中动态参数传递给 execlp() 函数

c - 格式参数太多。 C eclipse

python - 在Python中读取格式化的多行

c - 将文件中的行保存到新字符串中。 C

c - C中的gets()函数会自动在输入字符串的末尾添加一个NULL字符吗?

c - 无法使用 fgets() 函数读取循环结构内的字符串

c - 带有 Xcode 4.3.2 的 Mac OS X Lion 上的 Flex 和 Bison

c - VAD 从听模式切换到说模式

适用于多行的 Ruby 'gets'