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

The following code produces a very strange result when I run it.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    for ( ; ; )
    {
         char test;
         printf("Please enter 'w' ");
         scanf("%c", &test);
         printf("%c\n", test);
         if (test == 'w')
         {
              printf("Working\n");
         }
         else
         {
              printf("ERROR\n");
              return 0;
         }
     }
}

What I want to happen is for the whenever I input 'w' it continues the loop so I can input 'w' again. What it does though is go to the else statement even though I input 'w'. It just seems to skip the scanf() line. I have asked everyone I know who knows C but they do not know how to solve it.

Somebody please help me out here!


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.


as Jens said. you have to ignore the newline '\n'

Adding a space at the beginning of the format specifier " %c" will ignore the newline '\n'

scanf(" %c", &test);

Using " %c" will also ignore other white spaces like \t space \b \v \r