In contrast to all the other format specifiers (%d, %f, ...) of scanf(), %c (and the lesser known %[ as well) doesn't skip whitespace when trying to match the user input. It reads the next available character, whatever that is.
One problem arises when you use scanf("%c", &c) several times consecutively, e.g. inside a loop. To send the input to your program, the user has to press the enter key which is also stored in the input buffer (represented as the newline character - \n). Thus if you continuously read single characters from the input buffer, you sooner or later come across the newline character and that's when your program probably acts strangely.
To see what is happening, run the following program:
Sample session:Code:#include <stdio.h> int main(void) { char c; do { printf("Enter a letter (q to quit): "); scanf("%c", &c); printf("You've entered >>%c<<\n", c); } while (c != 'q'); return 0; }
As you can see, every second scanf()-call reads the newline character which is still left in the input buffer (there would still be a newline character left after quitting the loop!)Code:Enter a letter (q to quit): a You've entered >>a<< Enter a letter (q to quit): You've entered >> << Enter a letter (q to quit): b You've entered >>b<< Enter a letter (q to quit): You've entered >> << Enter a letter (q to quit): q You've entered >>q<<
For a simple solution to this problem you could add a space before the format specifier like:
Now scanf() skips any whitespace characters (including newline) before reading the next character, resulting in the same behavior as with the other format specifiers.Code:scanf(" %c", &c);
Another approach is flushing the input buffer after every scanf()-call, but don't use fflush(stdin)!
See also the manpage for scanf() for more details.



3Likes
LinkBack URL
About LinkBacks



