scanf 如何知道它是否应该扫描一个新值?

How does scanf know if it should scan a new value?

我正在研究 scanf 的工作原理。

扫描其他类型变量后,char变量存储了一个white-space('\n')getchar()scanf("%c")。 为了防止这种情况,他们应该清除缓冲区。我用 rewind(stdin)

做到了

尽管 stdin 被倒带,但先前的输入值仍保留在缓冲区中。 我可以正常使用以前的值做一些事情。(没有运行时错误) 但是如果我再次尝试 scanf ,即使缓冲区中有正常值,scanf 也会扫描一个新值。 scanf 如何确定它是否应该扫描一个新值?

我用下面的代码找到了这个机制。

#include <stdio.h>
#define p stdin

int main() {
    int x;
    char ch;

    void* A, * B, * C, * D, * E;

    A = p->_Placeholder;
    printf("A : %p\n", A);//first time, it shows 0000
    scanf_s("%d", &x);

    B = p->_Placeholder;
    printf("B : %p\n", B);//after scanned something, I think it's begin point of buffer which is assigned for this process
    rewind(stdin);//rewind _Placeholder 

    C = p->_Placeholder;
    printf("C : %p\n", C);//it outputs the same value as B - length of x

    D = p->_Placeholder;
    printf("D : %c\n", ((char*)D)[0]);//the previous input value is printed successfully without runtime error. it means buffer is not be cleared by scanf
    scanf_s("%c", &ch, 1);//BUT scanf knows the _Placeholder is not pointing new input value, so it will scan a new value from console. How??

    E = p->_Placeholder;
    printf("E : %p\n", E);
    printf("ch : %c\n", ch);
}

你至少存在三个误区:

  • "char变量存储了一个white-space"
  • rewind(stdin) 清除缓冲区
  • _Placeholder 告诉你一些有趣的事情 scanf 如何处理白色 space

但是,对不起,none 这些都是真的。

让我们回顾一下scanf 实际上如何处理白色space。我们从两条重要的背景信息开始:​​

  • 换行符 \n 在大多数方面是一个普通的白色 space 字符。它像任何其他字符一样在输入缓冲区中占据 space。当您按下 Enter 键时,它到达输入缓冲区。
  • 解析完 % 指令后,scanf 总是在输入流中留下未解析的输入。

假设你写

int a, b;
scanf("%d%d", &a, &b);

假设你运行输入代码和类型

12 34

然后按回车键。会发生什么?

首先,输入流(stdin)现在包含六个字符:

"12 34\n"

scanf 首先处理您给它的两个 %d 指令中的第一个。它扫描字符 12,将它们转换为整数 12 并将其存储在变量 a 中。它在看到的第一个非数字字符处停止读取,即 23 之间的 space 字符。输入流现在是

" 34\n"

请注意 space 字符仍在输入流中。

scanf 接下来处理第二个 %d 指令。它不会立即找到数字字符,因为 space 字符仍然存在。但这没关系,因为像大多数(但不是全部)scanf 格式指令一样,%d 有一个秘密的额外功能:它会在读取和读取之前自动跳过白色 space 字符转换整数。所以第二个 %d 读取并丢弃 space 字符,然后读取字符 34 并将它们转换为整数 34,并将其存储在变量 b.

现在 scanf 完成了。输入流只包含换行符:

"\n"

接下来,让我们看一个略有不同的示例,但正如我们将看到的,实际上非常相似。假设你写

int x, y;
scanf("%d", &x);
scanf("%d", &y);

假设你运行输入代码和类型

56
78

(在两行中,表示您按了两次 Enter)。 现在会发生什么?

在这种情况下,输入流最终将包含这六个字符:

"56\n78\n"

第一个 scanf 调用有一个 %d 指令要处理。它扫描字符 56,将它们转换为整数 56 并将其存储在变量 x 中。它在它看到的第一个非数字字符处停止读取,即 6 之后的换行符。输入流现在是

"\n78\n"

注意换行符(两个换行符)仍在输入流中。

现在第二个 scanf 呼叫 运行s。它也有一个 %d 指令要处理。输入流中的第一个字符不是数字:它是换行符。不过没关系,因为%d知道如何跳过白色space。所以它读取并丢弃换行符,然后读取字符 78 并将它们转换为整数 78,并将其存储在变量 y.

现在第二个 scanf 完成了。输入流只包含换行符:

"\n"

这可能都是有道理的,可能看起来不足为奇,可能让你觉得,“好吧,这有什么大不了的?”重要的是:在这两个示例中,输入都包含最后一个换行符

假设,稍后在您的程序中,您还有一些其他输入需要读取。我们现在来到一个非常重要的决策点:

  • 如果下一个输入调用是对 scanf 的另一个调用,并且它涉及(许多)格式说明符之一,该格式说明符还具有跳过白色的秘密额外功能space,该格式说明符将跳过换行符,然后执行扫描和转换换行符之后的任何输入的工作,程序将按您预期的方式运行。

  • 但是如果下一个输入调用是 而不是 scanf 的调用,或者如果它是对 scanf 的调用涉及作为少数没有秘密额外功能的输入说明符之一,换行符将不会“跳过”,而是读取为实际输入.如果下一个输入调用是 getchar,它将读取 return 换行符。如果下一个输入调用是 fgets,它将读取 return 一个空行。如果下一个输入调用是 scanf%c 指令,它将读取 return 换行符。如果下一个输入调用是 scanf%[^\n] 指令,它将读取一个空行。 (在这种情况下,实际上 %[^\n] 将读取 nothing,因为它仍然在输入中留下 \n。)

在第二种情况下,“额外”的白色space 导致了问题。在第二种情况下,您可能会发现自己想要明确地“冲洗”或丢弃多余的白色space.

但事实证明,冲洗或丢弃scanf留下的多余白色space的问题是一个非常顽固的问题。您不能通过调用 fflush 来移植它。您不能通过调用 rewind 来移植它。如果你关心正确的、可移植的代码,你基本上有三个选择:

  1. 编写您自己的代码以显式读取和丢弃“额外”字符(通常,直到并包括下一个换行符)。
  2. 不要尝试混用 scanf 和其他电话。不要调用 scanf,稍后尝试调用 getcharfgets。如果您调用 scanf,然后在稍后使用缺少“秘密额外功能”的指令之一(例如 "%c")调用 scanf,则插入一个额外的 space在格式说明符之前导致 whitespace 被跳过。 (即使用 " %c" 而不是 "%c"。)
  3. 根本不要使用 scanf — 根据 fgetsgetchar.[=256= 进行 所有 的输入]

另见 What can I use for input conversion instead of scanf?


附录:scanf对白色space的处理常常令人费解。如果以上解释还不够,查看一些详细说明 scanf 内部工作原理的实际 C 代码可能会有所帮助。 (我要展示的代码显然不是您的系统实现背后的确切代码,但它是相似的。)

scanf 处理 %d 指令时,您可能会想象它会做这样的事情。 (预先警告:我要向您展示的第一段代码是不完整和错误的。我需要尝试三次才能正确。)

c = getchar();
if(isdigit(c)) {
    int intval;
    intval = c - '0';
    while(isdigit(c = getchar())) {
        intval = 10 * intval + (c - '0');
    }

    *next_pointer_arg = intval;
    n_vals_converted++;
} else {
    /* saw no digit; processing has failed */
    return n_vals_converted;
}

让我们确保了解这里发生的一切。我们被告知要处理 %d 指令。我们通过调用 getchar() 从输入中读取一个字符。如果该字符是数字,则它可能是组成整数的几个数字中的第一个。我们读取字符,只要它们是数字,我们就将它们添加到我们正在收集的整数值 intval 中。转换涉及减去常量 '0',将 ASCII 字符代码转换为数字值,然后连续乘以 10。一旦我们看到一个不是数字的字符,我们就完成了。我们将转换后的值存储到我们的调用者传递给我们的指针中(这里示意性地但近似地由指针值 next_pointer_arg 表示),然后我们将 1 加到变量 n_vals_converted 中以记录我们有多少个值已扫描并转换成功,最终为scanf的return值

另一方面,如果我们甚至没有看到一个数字字符,我们就失败了:我们立即 return,我们的 return 值是我们的值的数量'到目前为止已经成功扫描和转换(很可能是 0)。

但实际上这里有一个微妙的错误。假设输入流包含

"123x"

这段代码会成功扫描并把数字123转换为整数123,并将这个值存入*next_pointer_arg但是,它会读到字符x,在循环while(isdigit(c = getchar()))中调用isdigit失败后,x字符将被有效地丢弃:它不再在输入流中。

scanf 的规范说 应该这样做。 scanf 的规范说明未解析的字符应该保留在输入流中。如果用户实际上已经传递了格式说明符 "%dx",这意味着在读取和解析整数后,输入流中需要文字 x,而 scanf 将必须显式读取并匹配该字符。所以它不会在解析%d指令的过程中意外读取并丢弃x

所以我们需要稍微修改我们假设的 %d 代码。每当我们读到一个不是整数的字符时,我们必须按字面意思 将其放回输入流 ,以便其他人稍后阅读。 <stdio.h> 中实际上有一个函数可以执行此操作,与 getc 正好相反,称为 ungetc。这是代码的修改版本:

c = getchar();
if(isdigit(c)) {
    int intval;
    intval = c - '0';
    while(isdigit(c = getchar())) {
        intval = 10 * intval + (c - '0');
    }

    ungetc(c, stdin);    /* push non-digit character back onto input stream */

    *next_pointer_arg = intval;
    n_vals_converted++;
} else {
    /* saw no digit; processing has failed */
    ungetc(c, stdin);
    return n_vals_converted;
}

您会注意到我在代码的两个地方都添加了对 ungetc 的调用,在调用 getcharisdigit 之后,代码刚刚发现它读取了一个 不是 数字的字符。

阅读一个字符然后改变主意可能看起来很奇怪,这意味着您必须“取消阅读”它。在不阅读的情况下偷看即将出现的字符(以确定它是否是数字)可能更有意义。或者,读取一个字符并发现它不是数字,如果下一段要处理该字符的代码就在 scanf 中,将它保存在局部变量 c,而不是调用 ungetc 将其推回输入流,然后调用 getchar 再次从输入流中获取它。但是,在指出了其他两种可能性之后,我只想说,现在,我将继续使用使用 ungetc.

的示例

到目前为止,我已经展示了您可能想象中位于 scanf%d 的处理之后的代码。但到目前为止我展示的代码仍然明显不完整,因为它没有展示“秘密的额外力量”。它立即开始寻找数字字符;它不会跳过前导白色space。

那么,这是我的 %d 处理代码的第三个也是最后一个示例片段:

/* skip leading whitespace */
while(isspace(c = getchar())) {
    /* discard */
}

if(isdigit(c)) {
    int intval;
    intval = c - '0';
    while(isdigit(c = getchar())) {
        intval = 10 * intval + (c - '0');
    }

    ungetc(c, stdin);    /* push non-digit character back onto input stream */

    *next_pointer_arg = intval;
    n_vals_converted++;
} else {
    /* saw no digit; processing has failed */
    ungetc(c, stdin);
    return n_vals_converted;
}

初始循环读取并丢弃字符,只要它们是白色的space。它的形式与后面的循环非常相似,只要字符是数字就读取和处理字符。最初的循环将读取一个比它看起来应该多的字符:当 isspace 调用失败时,这意味着它刚刚读取了一个 non whitespace特点。但这没关系,因为我们正要读取一个字符以查看它是否是第一个数字。

[脚注:这段代码还远非完美。一个非常重要的问题是它没有对解析过程中出现的 EOF 进行任何检查。另一个问题是它不会在数字前查找 -+,因此它不会处理负数。另一个更晦涩的问题是,具有讽刺意味的是,像 isdigit(c) 这样看起来很明显的调用并不总是正确的 — strictly speaking 它们需要稍微笨拙地呈现为 isdigit((unsigned char)c).]

如果你还和我在一起,我在这一切中的目的是具体说明这两点:

  • %d 能够自动跳过前导白色的原因space 是因为 (a) 规范说它应该这样做,并且 (b) 它有明确的代码要做因此,正如我的第三个示例所示。

  • scanf 的原因总是在输入上留下未处理的输入(即, 它确实读取和处理的输入之后出现的输入) stream 是因为 (a) 再一次,规范说它应该这样做,并且 (b) 它的代码通常带有对 ungetc 或等价物的显式调用,以确保每个未处理的字符都保留在输入中,因为我的第二个例子说明了。

你的方法有一些问题:

  • 您使用了 FILE 对象 _Placeholder 的未记录的特定实现成员,它可能在不同平台上可用,也可能不可用,并且其内容无论如何都是特定于实现的。
  • 您使用 scanf_s(),它是 Microsoft 特定的所谓 secure 版本的 scanf():此功能是可选的,可能无法在所有平台。此外,Microsoft 的实现不符合 C 标准:例如,在 &ch 之后传递的大小参数在 VS 中记录为 UINT 类型,而 C 标准将其指定为 size_t ,在 Windows 的 64 位版本上具有不同的大小。

scanf() 使用起来相当棘手:即使是经验丰富的 C 程序员也会被它的许多怪癖和陷阱所困扰。在您的代码中,您测试 %d%c,它们的行为非常不同:

  • for %d, scanf() 将首先读取并丢弃任何白色 space 字符,例如 space、TAB 和换行符,然后读取可选符号 +-,然后它期望读取至少一个数字并在它获得一个不是数字的字节时停止并将该字节留在输入流中,用 ungetc() 或将其推回相等的。如果无法读取任何数字,则转换失败并且第一个非数字字符在输入流中处于待处理状态,但之前的字节不一定被推回。
  • 处理 %c 更简单:读取单个字节并将其存储到 char 对象中,或者如果流位于文件末尾则转换失败。

如果输入流绑定到终端,则在 %d 之后处理 %c 是棘手的,因为用户将在 %d 预期的数字之后输入一个换行符,并且这个换行符将是立即阅读 %c。通过在格式字符串中的 %c 之前插入 space,程序可以忽略 %c 预期字节之前的白色 space:res = scanf(" %c", &ch);

为了更好地理解 scanf() 的行为,您应该输出每个调用的 return 值和通过 ftell() 获得的流当前位置。首先将流设置为二进制模式也更可靠,因为 ftell() 的 return 值恰好是文件开头的字节数。

这是修改后的版本:

#include <stdio.h>

#ifdef _MSC_VER
#include <fcntl.h>
#include <io.h>
#endif

int main() {
    int x, res;
    char ch;
    long A, B, C, D;

#ifdef _MSC_VER
    _setmode(_fileno(stdin), _O_BINARY);
#endif

    A = ftell(stdin);
    printf("A : %ld\n", A);

    x = 0;
    res = scanf_s("%d", &x);

    B = ftell(stdin);
    printf("B : %ld, res=%d, x=%d\n", B, res, x);

    rewind(stdin);
    C = ftell(stdin);
    printf("C : %ld\n", C);

    ch = 0;
    res = scanf_s("%c", &ch, 1);
    D = ftell(stdin);
    printf("D : %ld, res=%d, ch=%d (%c)\n", D, res, ch, ch);

    return 0;
}

下面是一些说明 %d 转换说明符行为的代码;它可能有助于理解 scanf 的那个方面是如何工作的。这不是它在任何地方实际实现的方式,但它遵循相同的规则(更新以处理前导 +/- 符号、检查溢出等)。

#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>

/**
 * Mimics the behavior of the scanf %d conversion specifier.
 * Skips over leading whitespace, then reads and converts
 * decimal digits up to the next non-digit character.
 *
 * Returns EOF if no non-whitespace characters are
 * seen before EOF.
 *
 * Returns 0 if the first non-whitespace character
 * is not a digit.
 *
 * Returns 1 if at least one decimal digit was
 * read and converted.
 *
 * Stops reading on the first non-digit
 * character, pushes that character back
 * on the input stream.
 *
 * In the event of a signed integer overflow,
 * sets errno to ERANGE.
 */
int scan_to_int( FILE *stream, int *value )
{
  int conv = 0;
  int tmp = 0;
  int c;
  int sign = 0;

  /**
   * Skip over leading whitespace
   */
  while( ( c = fgetc( stream ) ) != EOF && isspace( c ) )
    ; // empty loop

  /**
   * If we see end of file before any non-whitespace characters,
   * return EOF.
   */
  if ( c == EOF )
    return c;

  /**
   * Account for a leading sign character.
   */
  if ( c == '-' || c == '+' )
  {
    sign = c;
    c = fgetc( stream );
  }

  /**
   * As long as we see decimal digits, read and convert them
   * to an integer value.  We store the value to a temporary
   * variable until we're done converting - we don't want
   * to update value unless we know the operation was
   * successful
   */
  while( c != EOF && isdigit( c ) )
  {
    /**
     * Check for overflow.  While setting errno on overflow
     * isn't required by the C language definition, I'm adding
     * it anyway.  
     */
    if ( tmp > INT_MAX / 10 - (c - '0') )
      errno = ERANGE;

    tmp = tmp * 10 + (c - '0');
    conv = 1;
    c = fgetc( stream );
  }

  /**
   * Push the last character read back onto the input
   * stream.
   */
  if ( c != EOF )
    ungetc( c, stream );

  /**
   * If we read a sign character (+ or -) but did not have a
   * successful conversion, then that character was not part
   * of a numeric string and we need to put it back on the
   * input stream in case it's part of a non-numeric input.
   */
  if ( sign && !conv )
    ungetc( sign, stream );

  /**
   * If there was a successful read and conversion,
   * update the output parameter.
   */
  if ( conv )
    *value = tmp * (sign == '-' ? -1 : 1);

  /**
   * Return 1 if the read was successful, 0 if there
   * were no digits in the input. 
   */
  return conv;
}

/**
 * Simple test program - attempts to read 1 integer from
 * standard input and display it.  Display any trailing
 * characters in the input stream up to and including
 * the next newline character.
 */
int main( void )
{
  int val;
  int r;

  errno = 0;

  /**
   * Read the next item from standard input and
   * attempt to convert it to an integer value.
   */
  if ( (r = scan_to_int( stdin, &val )) != 1 )
    printf( "Failed to read input, r = %d\n", r );
  else
    printf( "Read %d%s\n", val, errno == ERANGE ? " (overflow)" : "" );

  /**
   * If we didn't hit EOF, display the remaining
   * contents of the input stream.
   */
  if ( r != EOF )
  {
    fputs( "Remainder of input stream: {", stdout );
    int c;
    do {
      c = fgetc( stdin );
      switch( c )
      {
        case '\a': fputs( "\a", stdout ); break;
        case '\b': fputs( "\b", stdout ); break;
        case '\f': fputs( "\f", stdout ); break;
        case '\n': fputs( "\n", stdout ); break;
        case '\r': fputs( "\r", stdout ); break;
        case '\t': fputs( "\t", stdout ); break;
        default: fputc( c, stdout ); break;
      }
    } while( c != '\n' );

    fputs( "}\n", stdout );
  }

  return 0;
}

一些示例 - 首先,我们发出 EOF 信号(在我的例子中,通过键入 Ctrl-D):

$ ./convert 
Failed to read input, r = -1

接下来,我们传入一个非数字字符串:

$ ./convert 
abcd
Failed to read input, r = 0
Remainder of input stream: {abcd\n}

由于没有任何转换,输入流的其余部分包含我们键入的所有内容(包括按 Enter 的换行符)。

接下来,一个带有非数字尾随字符的数字字符串:

$ ./convert 
12cd45
Read 12
Remainder of input stream: {cd45\n}

我们在 'c' 处停止读取 - 只有前导 12 被读取和转换。

几个用白色分隔的数字字符串space - 只转换第一个字符串:

$ ./convert 
123 456 789
Read 123
Remainder of input stream: {\t456\t789\n}

和前导白色的数字字符串space:

$ ./convert 
      12345
Read 12345
Remainder of input stream: {\n}

处理前导标志:

$ ./convert 
-123abd
Read -123
Remainder of input stream: {abd\n}

$ ./convert 
    +456
Read 456
Remainder of input stream: {\n}

$ ./convert 
-abcd
Failed to read input, r = 0
Remainder of input stream: {-abcd\n}

最后,我们添加了一个溢出检查——请注意,scanf 不是 C 语言标准所要求的检查溢出的条件,但我认为这样做很有用:

$ ./convert 
123456789012345678990012345667890
Read -701837006 (overflow)

输入流的剩余部分:{\n} %d%i%f%s 等,都跳过前导的白色space,因为白色space 在那些中没有意义案例除了充当输入之间的分隔符。 %c%[ not 跳过前导白色 space,因为它 可能 对那些人有意义特定的转换(有时您 知道您刚刚阅读的字符是 space、制表符还是换行符)。

正如史蒂夫指出的那样,在 C stdio 例程中处理 whitespace 一直是一个棘手的问题,没有任何一种解决方案总是最好的,特别是因为不同的库例程处理它不同。