简体   繁体   English

scanf格式字符串中“%c”之后的空格将忽略最后一个字符

[英]blank space after “%c” in scanf format string ignores last character

#include <stdio.h>

int main(void)
{
    char c;
    while (scanf(" %c ", &c) != EOF)
        printf("you typed: %c \n", c);

    return 0;
}

I can just put blank space before %c like " %c" to let scanf read a single character and skip any white spaces, but if I put another blank space after %c there comes problems: 我可以在%c之前放置空格,例如" %c"以使scanf读取单个字符并跳过任何空格,但是如果我在%c之后放置另一个空格,则会出现问题:

a s d f
you typed: a
you typed: s
you typed: d
1 2 3
you typed: f
you typed: 1
you typed: 2

so why does it leave last character in input stream? 那么为什么在输入流中保留最后一个字符呢? Even though I actually typed "asdf " with tailing space. 即使我实际上键入了带有尾部空格的"asdf "

In fact scanf leaves "f \\n" unread, right? 实际上scanf会使"f \\n"未被读取,对吗?

btw in the case of " %c" there's no problem as expected. 顺便说一句,在" %c"的情况下,没有任何问题。

From the draft of the C11 standard : 根据C11标准草案

7.21.6.2 The fscanf function 7.21.6.2 fscanf函数

[...] [...]

5. A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. 5.由空格字符组成的指令通过读取输入直到第一个非空格字符(仍未读取)来执行,或者直到无法再读取其他字符为止。 The directive never fails. 该指令永远不会失败。

This means that a whitespace character in the format string of *scanf will read and discard all whitespace characters until a non-whitespace character is encountered . 这意味着*scanf格式字符串中的空白字符将读取并丢弃所有空白字符, 直到遇到非空白字符为止

So, even if you input "asdf " , your scanf , after consuming the f , would read and discard the final space and would wait for further input as it hasn't encountered a non-whitespace character yet. 因此,即使您输入"asdf " ,使用f之后的scanf也将读取并丢弃最终空间, 并且由于尚未遇到非空白字符,因此将等待进一步的输入。

You can close the stream by sending in an EOF signal so that the scanf will stop scanning and return EOF . 您可以通过发送EOF信号来关闭流,以便scanf将停止扫描并返回EOF Or you could remove that space and revert it to " %c" which you originally had. 或者,您可以删除该空间并将其还原为最初具有的" %c"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM