C Error Notes
Problems with %c
scanf()
only takes the characters it needs from the buffer, but this can cause issues when using %c
. Consider the following program. When scanf()
reads an integer, it leaves behind a newline character ('\n'
) in the input buffer. The next time scanf()
is called with %c
, it thinks this leftover '\n'
is the input character. Because of this, the program never gets to read the tax status input from the buffer.
Buffer?
A buffer is like a temporary storage spot in a computer's memory. It holds data for a short time while it's being moved from one place to another.
#include <stdio.h>
int main(void)
{
int items;
char status; // tax status g or p
printf("Number of items : ");
scanf("%d", &items);
printf("Status : ");
scanf("%c", &status); // ERROR: assigns \n to variable 'status'
// and will not pause for user input
printf("%d items (%c)\n", items, status);
return 0;
}
The above program produces the following output:
Number of items : 25
Status : 25 items (
)
Notice how the newline character (
'\n'
) (which was assigned to the tax status variable) places the closing parenthesis on a newline.
Method-1:
scanf("%d", &items);
scanf("%c%c", &junk, &status); // store one character in junk first
Method-2:
scanf("%d", &items);
scanf("%*c%c", &status); // discard(ignore) one character first
Method-3:
scanf("%d", &items);
scanf(" %c", &status); // discard(ignore) all whitespace first
Method-4:
scanf("%d%*c", &items); // discard(ignore) newline ('\n')
scanf("%c", &status);
Method-5:
scanf("%d", &items);
clear(); // call a custom function to clear the buffer
scanf("%c", &status);