Using getchar() in a while loop
Solution 1:
Because you typed 'a
' and '\n
'...
The '\n
' is a result of pressing the [ENTER]
key after typing into your terminal/console's input line. The getchar()
function will return each character, one at a time, until the input buffer is clear. So your loop will continue to cycle until getchar()
has eaten any remaining characters from the stdin
stream buffer.
If you are expecting the stdin
input buffer to be clear when calling getchar()
then you should flush stdin
with while((ch=getchar())!='\n'&&ch!=EOF);
to consume any previous contents in the buffer just before calling getchar()
. Some implementations (ie. many DOS/Windows compilers) offer a non-standard fflush(stdin);
Solution 2:
Because in some implementations of getchar() when you press the key 'x' and ENTER, there are two caracters in the buffer (the 'x' and a newline char). (I know, this is a little dumb) You should skip newlines in your loop.
Update: this was already answered here: Where does `getchar()` store the user input?