为什么在加scanf格式串前导空格建议? [英] Why is adding a leading space in a scanf format string recommended?
问题描述
我目前正在读这本书C11编程的初学者,并在scanf()的章这样说的:
I am currently reading this book "C11 Programming for beginners" and in the scanf() chapter it says:
总是第一个控制串字符前加一个空格,以确保准确的文字输入。如:
"Always add a leading space before the first control string character to ensure accurate character input." As in:
scanf(" %s", whatever);
控制字符串%S,收到了空间。
我知道这听起来pretty不言自明,但我真的不明白有什么可以去错了,这个空间如何确保准确的文字输入。
The control string %s, has a space before it. I know it sounds pretty self-explanatory, but I don't really get what could go wrong, and how this space ensures accurate character input.
先谢谢了。
推荐答案
@WhozCraig也指出缺点这个建议。它自带无理性的,也不详细。而且它并不适用于%S
为%S
消耗了领先的空白带或不带领先的空间。
@WhozCraig well stated shortcomings to this advice. Its comes without rational nor detail. Further it does not apply to "%s"
as "%s"
consumes leading white-space with or without a leading space.
一个领先的空白,无论是,
'\\ T'
,的'\\ n'
等方面都做同样的事情:直接 scanf()的
来消费,而不是存储可选领先的空白字符
。这是从previous scanf()的
不消耗用户的的'\\ n'
典型用法有用在<大骨节病>输入骨节病>
A leading white-space, be it ' '
, '\t'
, '\n'
, etc. all do the same thing: direct scanf()
to consume and not store optional leading white-space char
. This is useful as typical usage of previous scanf()
does not consume the user's '\n'
from the Enter
scanf("%d", &some_int);
scanf("%c", &some_char); // some_char is bound to get the value '\n'
所有 scanf()的
输入符忽略前导空格,除了3:%C
,%N
,%[]
。
All scanf()
input specifiers ignore leading spaces, except 3: "%c"
, "%n"
, "%[]"
.
简单指令的做的使用如以下前导空格受益。 previous遗留的空白之前消耗的$
。
Simply directive do benefit with the leading space as in the following. Previous left-over white-space is consumed before '$'
.
int Money;
scanf(" $%d", &Money);
通常情况下,虽然不总是前的前导空格%C
是读书时是有益的一个字符
的用户输入。
Often, though not always a leading space before "%c"
is beneficial as when reading a single char
of user input.
char ch;
scanf(" %c", &ch);
什么是最错误的建议是,1当使用%S
,提供一个宽度参数)是稳健的code必要的,2)返回值应检查
What is most wrong with the advice is that 1) when using "%s"
, supplying a width parameter is essential to robust code and 2) the return value should be checked.
char buf[30];
int cnt = scanf("%29s", buf);
if (cnt != 1) Handle_NoInput_or_EOF_IOError();
最后,建议使用与fgets()
在 scanf()的
作为一个可以 - 这是通常的案例。
Lastly, recommend to use fgets()
over scanf()
as one can - which is the usually the case.
这篇关于为什么在加scanf格式串前导空格建议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!