The %c
conversion specifier won't skip over leading whitespace characters, so it's picking the newline character that's still in the input stream from the previous entry. IOW, suppose you type in a length of 10. The input stream then contains the characters '1'. '0', and '\n'. The first scanf("%d", &length)
call consumes the '1' and the '0', but leaves the '\n' in the input stream. Thus, the first scanf("%c", &key[i])
reads the '\n' character, not the character you entered.
The workaround for this is to add a blank space in the format string before the %c
conversion specifier: scanf(" %c", &key[i])
. This will tell scanf
to skip over any learning whitespace and read the first non-whitespace character into key[i]
.