[previous_group] [previous] [up] * [next_group]

A Few More Things about Characters

Mixing character and numeric input

One thing we need to be careful about is mixing numeric and character input. This is because of the difference in the way scanf() handles the two kinds of input.

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.

How can we fix this?

When switching between numeric and character input, we know that there is at least one whitespace character still in the buffer after reading the data, the '\n'. We can modify the scanf() call to take this into account:
     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.

Menu driven programs

One last topic in Chapter 4 concerns using character input and the switch statement to write menu driver programs. For example, the payroll program. We will look at this technique in more detail in later example programs.
[up] to Overview.

[next_group]