Recall that scanf() using numeric conversion specifiers (%d or %f) is "white space tolerant", i.e. when reading from the buffer, scanf() will skip over any white space (spaces, tabs and newlines) until it finds the first digit of a numeric data item. However, when reading character input (using %c), scanf() does NOT skip white space, but reads each and every character. getchar() behaves the same for reading characters.
This can cause some unusual behavior in programs that read numeric data, and then read characters. Consider the simple example program, chrtest.c.
scanf("%d%*c",&number);The "%*c" says to read one character, but throw it away. We do not need to give a character variable address to scanf(), since it will not be saving the character read.
This will work as long as we know that only the return will be in the buffer. However, users might add other space characters to the input. It would be safer to make sure the buffer is empty before we try to read characters. This is called flushing the buffer. We can write a macro to do this for us:
#define FLUSH while(getchar()!='\n');We can add this to chrtest.c by defining FIX_IT.
We have already seen this effect in real programs. Consider the improved guessing game again. When we ask it the player if they want to play again, the '\n' in the buffer from the last guess made will serve as the answer character, which means we WILL play again, whatever we do.