char ch;
how we can assign constant values to such a variable:
c = 'r';
and how to read and print character variables:
scanf("%c",&ch);
printf("%c\n",ch);
As a simple example program using characters, consider the program
to count the number of characters in a file (the standard input).
The code is in
count.c.
Because character I/O operations are so common in C programs, the stdio library provides two additional functions for reading and printing character variables:
That is why we had the strange behavior in the improved guess.c - the newline in the buffer after we enter the guess is read by the scanf() as the player's response. Since '\n' is not 'n', the while loop plays another game.
To fix the problem, we need to flush any extra characters from the input buffer before reading the player's anwer character. We do this by reading all characters in the buffer, up to and including the '\n' character.
We have defined a macro, FLUSH, to do that:
# define FLUSH while(getchar() != '\n');and use the macro to flush the buffer before reading the keep_playing character.