It is a naive solution to the unused buffered input problem. Your prof recognises the problem, but it seems does not know how to solve it properly.
If you use formatted input, only characters entered that match the format specifier are used. So if for example the last input requested a decimal integer using %d, you might enter at the console:
123<newline>
The formatted input will consume the "123", leaving the <newline>
buffered. An unformatted input such as getchar() will consume that and return immediately. Since this is not what you want, your prof has used the "just add another getchar() kludge". This works only if the user enters the expected input. A hamfisted typist might type:
123w<newline>
Now the first getchar() gets the 'w', the second gets the <newline>
, and your program terminates before you intended it to, and in a GUI environment, if the terminating process owns the window it is running in, then the OS closes it.
A more robust solution is to repeatedly call getchar() until the <newline>
is found:
while( getchar() != '\n' ) { /*do nothing*/} ;
getchar() ; /* wait */
Of course if the previous input was a character, you need to check it was not already a <newline>
:
while( ch != '\n' && getchar() != '\n' ) { /*do nothing*/} ;
getchar() ; /* wait */
Rather than putting the flush loop at the end just before the 'wait' input call, it is better to perform the buffer flush after every input that requires it. This is because that is where you know you need it, and how it should be coded. I tend to write wrapper functions for the input types I need.