忽略所有输入字符,直到输入 'a' - 在 C 中使用 scanf

Ignoring all input characters until 'a' is entered - using scanf in C

我正在尝试 C 上的基本代码片段。我的目的是忽略所有字符,直到用户输入 'a',然后将下一个非空白字符复制到 x。

#include <stdio.h>

int main()
{
    char x ;
    printf ("Input character - ") ;
    scanf  (" a %c", &x) ;
    printf ("x=%c is the input", x) ;
    return 0 ;
}

我在控制台中输入如下:

a <enter>
s <enter>

我得到的输出为:x=s is the input。这是正确的。

但是当我在控制台中输入时:

b <enter>

执行突然结束,我得到的输出为:x= is the input.

我不明白这种行为。我希望程序忽略 'b' 和后续字符,直到用户输入 'a' 为止。我是否错误地解释了 scanf 语句?

Did I interpret the scanf statement wrongly?

是的。假设 scanf 通常是这样的:

  • 从输入中读取一个字符
  • 检查它是否匹配格式字符串
  • 如果匹配,scanf 继续到字符串的下一部分
  • 如果不匹配,scanf调用ungetc并退出
  • scanf returns 扫描的参数数量或 EOF 如果出现错误或没有扫描参数。

如果您执行 scanf(" a %c", &x);,然后键入 b <enter>,则:

  • scanf 读取 b
  • b 不匹配 " " (space)
    • " " space 很神奇,它匹配 零个或多个 白色 space 个字符
    • 所以scanf继续
    • b 不匹配 a
  • scanf 呼叫 ungetc('b')
  • scanf returns 与 EOF

在这种情况下,x 永远不会被赋值,x 是未初始化的并且包含一些垃圾值。很可能在输出中 x=>here< is 有一些不可打印的不可见字符。

通过使用 scanf("a%c",&x); 您可以预先格式化要接受的输入,如果它像 'ab' 、 'ac' 、 'aa' 并给出 'b' , 'c' 和 'a' 分别作为 o/p,并且不会接受任何类似的东西。 (也可以分别为 'aaa' 、 'abc' 作为 'a' 、 'b' 等输入提供 o/p

对于您的任务,您可以尝试以下代码:-(已完全测试)

#include <stdio.h>

int main()
{
    char x ;
    do{
        scanf("%c",&x);
    }while(x != 'a');      //Read until x is not 'a'
    
    scanf("%c",&x);        //Read next character from standard input into x
    printf("%c",x);        //And then print x
    return 0 ;
}