INFO: Next scanf/fscanf Apparently Is Skipped During Run Time (42075)



The information in this article applies to:

  • The C Run-Time (CRT), when used with:
    • Microsoft C for MS-DOS
    • Microsoft Visual C++ for Windows, 16-bit edition 1.0
    • Microsoft Visual C++ for Windows, 16-bit edition 1.5
    • Microsoft Visual C++, 32-bit Editions 1.0
    • Microsoft Visual C++, 32-bit Editions 2.0
    • Microsoft Visual C++, 32-bit Editions 2.1
    • Microsoft Visual C++, 32-bit Editions 4.0
    • Microsoft Visual C++, 32-bit Editions 5.0
    • Microsoft Visual C++, 32-bit Editions 6.0

This article was previously published under Q42075

SUMMARY

When a function of the scanf() family reads a white-space character--blank (' '), tab ('\t'), or newline ('\n')--it does not ordinarily store that character into the location provided by the argument pointer. However, as documented in the Microsoft C Run-Time Library Reference, if the %c type field format specifier is used, the scanf() functions will store a white- space character. This behavior can cause unexpected results.

MORE INFORMATION

After the first character is read in the sample code below, the following white-space character that is still in the internal buffer for stdin is read and stored by the second scanf(). This effectively causes the second prompt to be skipped (the message is printed, but the program does not wait to accept a character).

To obtain the desired behavior, use the format specifier %1s instead of %c. Don't forget to pass scanf() an array of at least two characters, because the scanf() family will also store a terminating character ('\0') when "s" is used for the type field format.

Alternatively, the fflush() function can be used to flush all characters, including white-spaces, out of the specified buffer after each scanf() or fscanf(). Use flushall() to flush all file buffers.

Sample Code

/* Compile options needed: none
*/ 

#include <stdio.h>

void main()
{
  char a,b[2];
  do
  {
      printf( "Enter a single character\n" );
      scanf( "%c", &a );

      printf( "Enter another character\n" );
      scanf( "%c", b );
  }
  while ( a != 'y' );
}
				

Modification Type:MinorLast Reviewed:7/5/2005
Keywords:kbcode kbCRT kbinfo KB42075