Microsoft KB Archive/42075

= INFO: Next scanf/fscanf Apparently Is Skipped During Run Time =

Article ID: 42075

Article Last Modified on 7/5/2005

-

APPLIES TO

 The C Run-Time (CRT), when used with:  Microsoft C Professional Development System 6.0a

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.1</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul>

 Microsoft Visual C++ 5.0 Standard Edition</li></ul>

 Microsoft Visual C++ 6.0 Service Pack 5</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q42075

<div class="notice_section">

<div class="summary_section">

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.

<div class="moreinformation_section">

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 &quot;s&quot; 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


 * 1) include <stdio.h>

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

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

Keywords: kbinfo kbcrt kbcode KB42075

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.