Why is my professor using two getchar (); at the end of our C tutorials?
Assuming you have something like
int main ( void ) { int input; scanf ( "%d", &input ); printf ( "The input is %d.\n", input ); getchar(); getchar(); return 0; }
Two, because scanf will not be returned until the enter key is pressed, but any other characters entered in the input buffer will be entered from the input and \ n \.
So, if you run above and enter 1234 Enter , the program will stop after printing The input is 1234. until you press Enter again. The first getchar reads '\n' associated with the first Enter . If you enter something else, for example 1234 Space Enter , the program does not pause, since the first getchar will read the space. Two getchar may be insufficient, and you have entered the code to print the response in the code to process the input.
And what is the “best way” to do this?
There are various standard ways to read input in C. There are also platform-specific ways to ignore text in the input buffer, but you do not need to do this if you use fgets to read an input line instead of from scanf to read input from the last input line.
fgets (reading input to '\ n' or the end of the file), followed by sscanf (parsing the line for input), is safe from buffer overflows and will absorb any additional input and line ending '\ n'
#include <stdio.h> int main ( void ) { int input; char buf[16] = ""; fgets ( buf, sizeof buf, stdin ); sscanf ( buf, "%d", &input ); printf ( "The input is %d.\n", input ); fflush ( stdout ); getchar(); return 0; }
Clearing stdout after printf usually not required for the IO terminal, but it can be if you connect it to the disk (usually, when you register an emergency program, it will lose the most interesting bit before the failure, if you have not cut it).
Since fgets reads and includes the end of the line, there are no characters in the buffer, so you only need one getchar and a bit inconvenient input, for example 1234 Space Enter does not end the program without pausing.
However, most of the time you do not need to wait after starting the console application - on Linux or other Unix systems, the console usually opens and the program starts there, after which control returns to the shell. On the Windows IDE, such as Visual Studio, they usually start the program and pause it using something like:
"C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause"
Either you can open cmd.exe and run it there, or you can run it using the .pif shortcut and check the box so that it does not close the console when exiting, or you can create a batch file that starts it and pauses.
You really only need to pause the program if you are running Windows and you use the debugger to start it and you have not set breakpoints.