Why is my prof using two getchar(); at the end of our C program 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
won't return until after an enter is pressed, but there will be the '\n' from the enter and any other characters you have entered in the input buffer.
So if you run the above and input 1234
Enter, the program will pause after printing The input is 1234.
until you then press Enter again. The first getchar
reads the '\n'
associated with the first Enter. If you input something else, such as 1234
SpaceEnter, the program will not pause, as first getchar
will read the space. Two getchar
s might not be enough, and you've interspersed the code for printing the response into the code for handling the input.
And what is the "better way" for this?
There are various standard ways of reading input in C. There are also platform specific ways of ignoring text in the input buffer, but you shouldn't need to do that if you use fgets
to read a line of input instead of scanf
to read some input from the last line entered.
fgets
( read input until '\n' or end of file ) followed by sscanf
( parse a string for input ) is safe from buffer overruns, and will absorb any extra input and line terminating '\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;
}
Flushing stdout
after the printf
isn't normally needed for terminal IO, but can be if you're piping it to a disk ( typically when you're logging a crashing program it will lose the most interesting bit just before the crash if you don't flush ).
Because fgets
reads up to and including the end of the line, there are no characters left in the buffer so you only need one getchar
, and slightly awkward input such as 1234
SpaceEnter doesn't cause the program to terminate without pausing.
However, most of the time you don't need to wait after running a console application - on Linux or other Unix systems you typically have a console open and run the program there, after which control returns to the shell. On Windows, IDEs such as Visual Studio typically run the program and pause it using something like:
"C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause"
Or you can open cmd.exe and run it from there, or you can run it with a .pif shortcut and set the checkbox it not to close the console on exit, or you can create a batch file which runs it and pauses.
You really only need to make the program pause itself if you're on Windows and you're using a debugger to run it and you haven't set any breakpoints.