The problem is that when you enter a character for scanf("%c", &d);
, you press the enter key. The character is consumed by the scanf
and the newline character stays in the standard input stream(stdin
). When scanf
(with %c
) is called the next time, it sees the \n
character in the stdin
and consumes it, and thus does not wait for further input.
To fix it, change
scanf("%c", &d);
to
scanf(" %c", &d);
// ^Note the space before %c
The space before the %c
instructs scanf
to scan any number of whitespace characters including none and stops scanning when it encounters a non-whitespace character. Quoting the standard:
7.21.6.2 The fscanf function
[...]
- A directive composed of white-space character(s) is executed by reading input up to the
first non-white-space character (which remains unread), or until no more characters can
be read. The directive never fails.
The reason that using %d
worked is that the %d
format specifier automatically skips whitespace characters and since \n
is a whitespace character, %d
does not scan it. Quoting the standard again:
7.21.6.2 The fscanf function
[...]
- Input white-space characters (as specified by the
isspace
function) are skipped, unless
the specification includes a [
, c
, or n
specifier. 284