Are there any dangers to using %*c in scanf() to clear the buffer when necessary.
For example:
char c;
for (int i = 0; i < 5; i++) {
scanf("%c%*c", &c);
}
Or
char* str;
char c;
int i;
scanf("%s", str);
scanf("%d%*c", &i);
scanf("%c%*c", &c);
Should there be any concern for buffer overflows or other security issues?
There seems to be no formal documentation for the usage of the asterisk in scanf this way for C (EDIT This is not true), so I’m having trouble finding out exactly what happens to the extra characters that are inputted.
Is there a better way of clearing the scanf buffer in C?
You’ll have better luck conceptualizing the task you’re trying to accomplish as “how do I read and discard any junk that the user might’ve typed after what I care about”, which will lead you to constructs such as
But also, you can avoid the entire problem by not using
scanfin the first place, which is a good idea for several other reasons. Read entire lines withgetline, if you have it, orfgetsif you don’t, and parse them by hand.