C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
Solution 1:
scanf("%c")
reads the newline character from the ENTER key.
When you type let's say 15
, you type a 1
, a 5
and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d")
reads the 1
and the 5
, interpreting them as the number 15
, but the newline character is still in the input buffer. The scanf("%c")
will immediately read this newline character, and the program will then go on to the next scanf("%d")
, and wait for you to enter a number.
The usual advice is to read entire lines of input with fgets
, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a getchar()
after each scanf("%d")
.
Solution 2:
The basic problem is that scanf()
leaves the newline after the number in the buffer, and then reads it with %c
on the next pass. Actually, this is a good demonstration of why I don't use scanf()
; I use a line reader (fgets()
, for example) and sscanf()
. It is easier to control.
You can probably rescue it by using " %c"
instead of "%c"
for the format string. The blank causes scanf()
to skip white space (including newlines) before reading the character.
But it will be easier in the long run to give up scanf()
and fscanf()
and use fgets()
or equivalent plus sscanf()
. All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf()
after it fails.
You should also, always, check that you get a value converted from scanf()
. Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.
Solution 3:
Try adding a space in the scanf.
scanf(" %d", &var);
// ^
// there
This will cause scanf()
to discard all whitespace before matching an integer.