INF: Next scanf/fscanf Appears to Be Skipped During Run Time

ID Number: Q42075

5.00 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

In Microsoft C versions 5.0, 5.1, 6.0, 6.0a, 6.0ax, and C/C++ version

7.0, after the first character is read in the sample code below, the

following newline character (that is, linefeed, 0A hex) that is still in

the internal buffer for stdin is read by the second scanf() [or

fscanf()], causing the next prompt to be skipped during run time.

The "Microsoft Optimizing Compiler Run-Time Library Reference" states

the following in the description of the char format specifier:

White-space characters that are ordinarily skipped are read when %c

is specified; to read the next non-white-space character, use %1s.

To get the desired behavior, use the format specifier %1s instead of

%c. Do not forget to pass scanf() or fscanf() an array of two

characters, because scanf() and fscanf() will also store a terminating

character.

Alternatively, the fflush() function can be used to flush all

characters, including white space, out of the specified buffer after

each scanf() or fscanf(), or flushall() can be used to flush all file

buffers.

More Information:

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 ( b[0] != 'y' );

}

Additional reference words: 5.00 6.00 6.00a 6.00ax 7.00