Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my professor using two getchar();? [closed]

Tags:

c

Why is my prof using two getchar(); at the end of our C program tutorials?

And what is the "better way" for this?

like image 665
Zach Smith Avatar asked Sep 16 '09 13:09

Zach Smith


3 Answers

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.

like image 132
bleeeah Avatar answered Sep 29 '22 08:09

bleeeah


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));
like image 34
Lucas Avatar answered Sep 29 '22 06:09

Lucas


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 */;
like image 37
pmg Avatar answered Sep 29 '22 08:09

pmg