Why is my prof using two getchar(); at the end of our C program tutorials?
And what is the "better way" for this?
He is waiting for user input so that you can see the output to the program, otherwise it will just complete and the output will not be visible (depending on the OS). Take it out and give it a try.
He wants the console to stay open and wait for the user to press a key. I think to remember that depending on what happens in your professors program above the "getchar()". There might still be something in the buffer, so he added a second "getchar()". Not exactly the most elegant way to solve the problem.
Edit: Here is a little example. There is still a remaining "\n" in the buffer from the "scanf()" If you add a second "getchar()", you get the expected result. You have to flush the buffer before the "getchar()".
#include <stdio.h>
main()
{
int input;
scanf("%d", &input);
printf("The input is %d\n", input);
getchar();
return 0;
}
Edit 2: Here is a solution taken from here.
int c;
printf( "Press ENTER to continue... " );
fflush( stdout );
do c = getchar(); while ((c != '\n') && (c != EOF));
The best better way is not to add any code to try and keep the console window open: start your program right from the console window.
If you must start your program from the IDE and want the program to not terminate before the user presses Enter, one single getchar()
should do it.
The second best better way to make the program terminate after the user presses a key, is to always make sure there are no inputs pending and use one single getchar()
.
The reason your teacher uses 2 getchar()
, I guess, is that there is already a character in the input buffer from previous inputs. To consume all characters from the inputs, up to and including the ENTER, this is usual:
int ch;
/* ... */
printf("Press Enter"); fflush(stdout);
while ((ch = getchar()) != '\n' && ch != EOF) /* void */;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With