scanf ("%c") problem - When I enter a value for one scanf, it skips the second scanf. scanf(" %c)

Refer to the following screenshot.  When I entered a value for the first scanf, it skipped the second scanf.  i.e. It was like an [enter] was typed even though the user did not do so.

Screenshot. The second scanf was skipped, highlighted with yellow arrow.
Screenshot: The second scanf was skipped, highlighted with yellow arrow.

C code - Scanf problem
C code - scanf problem

What causes this problem?

  1. After the first scanf, the [enter] character is still in the input buffer.
  2. The second scanf("%c") will immediately read this [enter] character.  Hence, it accept [enter] as the input.  To the user, it appears that it skips the scanf.

How to fix the problem?

To solve the problem, insert a “space” before %c. i.e.

          scanf("   %c", &choice);

Why?

  1. The [enter] character was left in the input buffer after the first scanf.
  2. With the space before %c, it tells second scanf to ignore whitespace.  Without it, it will take the [enter] as the input.  That’s why it appears to skip the second scanf.

Fixing scanf problem with fflush.
Can I use fflush to solve the problem?

Some people use fflush(stdin) to solve the problem.  It does NOT work in certain compilers.  Why?

Because fflush(stdin) produces undefined behavior.  fflush is only defined by the C standard for output streams; undefined for input stream.

The following is the documentation for fflush.

int fflush( FILE *stream );

  • For output streams (and for update streams on which the last operation was output), writes any unwritten data from the stream's buffer to the associated output device.
  • For input streams (and for update streams on which the last operation was input), the behavior is undefined.
So, it's not a question of "how bad" this is. fflush(stdin) is plainly wrong, and you must not use it, ever.

Post a Comment

0 Comments