How to Pause a Program Using C++


Sometimes a program will reach a point where you want it to pause and wait for acknowledgement from the user before proceeding. For example, a program that prints hardcopy might display a message urging the user to prepare the printer for use (ie. check its status regarding power, paper and ink). The program should pause and wait for the user to press the Enter key before proceeding to the steps that print. Such action would be indicated in a flowchart like this:

The corresponding source code in the C++ language would require two statements calling two C++ methods:

     cin.ignore(); cin.get();

The cin.ignore() method clears any characters (such as a latent '\n') in the keyboard input buffer. The cin.get() method pauses the program until a new Enter characters is received in the buffer. It is typical to display a warning message about the pause first. For example:

cin.ignore(); // clear the input buffer
cout << "Press the Enter key to continue -";
cin.get(); // wait for input of Enter character
cout << "\nThank you. Continuing.\n";

The program will display the prompt "Press the Enter key to continue -", then wait for the user to press the Enter key, and afterwards proceed to the next step in the program. The Enter keystroke (\n) will not be stored.

An alternative approach to pausing a program that uses the operating system

An alternative technique that will accomplish the same result involves use of the standard command provided by the command-line interface (CLI) in any any operating system (OS) to pause until any key is pressed. The use of this approach requires a function capable of calling an OS CLI and passing to it a command recognized by that OS to pause. Most CLI's have a keyword named pause for this purpose. So the C++ command to call the OS and ask it to pause the program (currently running in its command window) would be:

system ("pause");

If the OS uses a different keyword to pause, then it should be substituted in place of the word pause in the statement above. Some compilers require that a library header file named cstdlib be included in the source code before the system keyword will be recognized. The C++ compiler directive to do this would be:

#include <cstdlib>

The advantage of using the system pause approach over the cin statements is that it allows the press of any key to continue; not just the Enter key. The disadvantage of this approach is that it requires knowledge of and dependence on the specific OS being used on the computer.

PATH: Instructional Server> COP 2000> Examples>