Screenshot: The second scanf was skipped, highlighted with yellow arrow. |
C code - scanf problem |
What causes this problem?
- After the first scanf, the [enter] character is still in the input buffer.
- 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?
- The [enter] character was left in the input buffer after the first scanf.
- 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?
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.
0 Comments