有人告诉我,当用户输入字符串时不应使用 scanf 。相反,大多数专家以及 StackOverflow 上的用户都使用 gets()。我从来没有在 StackOverflow 上问过为什么不应该使用 scanf 而不是 gets 来处理字符串。这不是实际的问题,但非常感谢对此问题的回答。
现在进入实际问题。我遇到过这种类型的代码 -
scanf("%[^\n]s",a);
这将读取一个字符串,直到用户输入一个新行字符,并将空格也视为字符串。
如果我使用有什么问题吗
scanf("%[^\n]s",a);
而不是得到?
听起来比 scanf 函数更优化,gets 纯粹专用于处理字符串。请让我知道这一点。
Update
This链接帮助我更好地理解它。
gets(3)
是危险的,应该不惜一切代价避免。我无法想象它的用途gets(3)
is not安全缺陷。
scanf(3)
's %s
这也是危险的——您必须使用“字段宽度”说明符来指示已分配的缓冲区的大小。如果没有字段宽度,这个例程就和gets(3)
:
char name[64];
scanf("%63s", name);
GNU C 库提供了a
modifier to %s
为您分配缓冲区。这个不可移植的扩展可能不太难正确使用:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)