Using getchar() in a while loop

Because you typed ‘aand\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);

Leave a Comment

tech