Problems with C scanf(“%c”) function to read characters one by one

This is because you type w followed by ENTER. So there are 2 characters in the input, 'w', followed by a newline (\n). The latter causes the else branch to be taken on the second iteration.

Note that standard input is line buffered when connected to a terminal. If you need to deal with characters immediately, there are ways to do that. See the comp.lang.c FAQ for details (“How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they’re typed?”).

Note that for robust programming it is a must to check the return value of scanf. It returns the number of successfully converted items. As shown, your code does not handle the case of end-of-file properly, i.e. when the user types Ctrl-D (assuming Unix terminal). Then scanf returns EOF and no conversion was performed, but you use test as if it contained a meaningful value.

Leave a Comment