C如何处理scanf中的尾随空格? [英] How does C treat trailing spaces in scanf?
问题描述
如果 scanf 语句的格式字符串中有空格,如下所示,
If a scanf statement has any white space in the format string, like as follows,
scanf(" %c",&abc);
然后它会跳过无限数量的空格,直到碰到一个字符为止.
因此, \ n p 作为输入会将 p 存储在 abc 中.
then it just skips over an unlimited number of white spaces until it hits a character.
So \n p as input would store p in abc.
使用此概念,我无法预测我键入的以下程序的输出.
Using this concept I am not able to predict the output of the following program that I typed.
char echo ;
do {
scanf ("%c ", &echo);
printf ("%c\n",echo);
} while (echo != '\n') ;
请注意,scanf语句中有一个跟踪空间.
Note that there is a trailing space in the scanf statement.
执行代码后,我得到以下行为.
它要求一个字符.我输入C
它要求一个字符.我输入我
打印C.
它要求一个字符.我输入R
它打印I.
它要求一个字符.我输入C
它显示R.
Upon execution of the code I get the following behaviour.
It asks for a character. I enter C
It asks for a character. I enter I
It prints C.
It asks for a character. I enter R
It prints I.
It asks for a character. I enter C
It prints R.
这将永远持续下去.如果我按换行符,那么它将跳过它.
为什么在开始时要求两个字符?它不应该执行 printf 语句吗?
为什么上一个输入的字符会在下一个输入中打印出来?
This goes on forever. If I press newline, then it just skips it.
Why does it ask for two characters in the beginning? Shouldn't it execute the printf statement?
Why is the character of the previous input get printed in the next one?
推荐答案
在 scanf
格式中,空格字符与输入中任意数量的空格(空格,制表符和换行符)匹配.
In scanf
format the space character matches any amount of white space (spaces, tabs and newlines) in the input.
因此,您输入 C +换行符
不会发生任何事情,因为 scanf
将字符 C
匹配为%c
并且 newline
被空格所占用.但是 scanf
将继续,直到得到不匹配的内容.因此,您可以在此处放置任意数量的空格,制表符和换行符.
So you enter C + newline
and nothing happens, as scanf
matched the character C
to %c
and the newline
is eaten by the space. But scanf
will continue until it gets something which does not match. So you can put any amount of spaces, tabs and newlines here.
当 scanf
读取不匹配的提示时,它将调用 ungetc(c,stdin)
将其放回stdin并返回.因此,空间将继续匹配,直到您放置其他内容为止.
When scanf
reads somewhing that does not match, it calls ungetc(c, stdin)
to put it back to stdin and returns. So the space will continue matching until you put something different.
这就是为什么当您键入 R +换行符
时返回最后一个 scanf
的原因.然后执行下一个 scanf
,它将 R
与%c
匹配,并将换行符与空格匹配.但是空间仍然匹配任意数量的空格.当您键入非空格字符时,它将结束.
That's why the last scanf
returns when you type R + newline
. Then the next scanf
executes, it matches R
with %c
and the newline with space. But space is still matching any number whitespaces. It will end when you type a non white-space character.
这篇关于C如何处理scanf中的尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!