There are a few questions floating around on stack overflow that, when synthesized, likely answer this question. However, I just wanted to make sure beyond any doubt that the following interpretation of a code segment is correct.
In "C Programming: A Modern Approach", the following code idiom involving a scanf()
function and a getchar()
function is occasionally seen. Consider the following example, taken from Page 392:
int main(void)
{
char code;
for (;;) {
printf("Enter operation code: ");
scanf(" %c", &code);
while(getchar() != '\n')
;
.../*other stuff*/
}
}
Here is my understanding of what is going on with the getchar()
function embedded within a while
loop.
When the user is prompted to enter a character, it is very possible that the user presses many buttons (e.g. abcdefg 12 3 , . f
) into the command terminal.
In the absence of the getchar()
line, scanf()
(which is embedded within an infinite loop) would otherwise iteratively chug through that input buffer.
i.e. On the first pass, code
would be assigned the character 'a'
and the input buffer would have bcdefg 12 3 , . f
remaining...on the second pass through the infinite for
loop, code
would be assigned character 'b'
and cdefg 12 3 , . f
would be remaining...etc.
However, by including the getchar()
line, we are effectively draining the input buffer so that prior to advancing to the \* other stuff *\
section, the input buffer is completely empty.
Is this the correct idea?
If it is, then my final question is why does the getchar()
line need to be written as != '\n'
. Couldn't I have written the condition as being not equal to literally anything? e.g. != ','
or !='d'
or != ' '
...etc.
Is it just for readability (i.e. conforming to the quasi-convention of using the Enter button to submit information to the computer)?
Thanks~