How to Clear the Screen in a C++ Program


Sometimes a programmer wants to erase the contents of a display screen (or in the case of our class, a "console window") and start new output at the top left (or "home") corner. This action is called "clearing the screen". It would be indicated in a flowchart like this:

Clear screen flowchart example

You may be surprised to learn that many programming languages do not have a keyword for this action despite it being such a common need. This is because different brands of display monitor require programs to output different codes to clear the screen, even in simple programs that use only a black and white console window for their output like those written in our class. Therefore, a compiler does not know what binary code to use for this action.

A solution to this problem is to make use of the fact that an operating system (OS) typically does know how to clear a console window (because the monitor's brand and model was identified when it was installed). So you can have your program send a command to the operating system to clear the console window and rely on the OS to do it. The command used by DOS and Windows to clear a console window is "cls". Sending a command to the OS from C++ source code often requires that you include a header library named "cstdlib". You can then use its function named "system" to send the command at the point in your program where you want the screen cleared. In your C source code you would write the compiler directive:

    #include <cstdlib>

in the declaration section at the top of the code and then place the function call

    system("cls");

at the point in your code where you want to clear the screen.

When testing the program in the compiler, there will be no apparent indication that this command did anything - because the compiler opens a newly created (blank) window for the program which is already clear. However, if tested outside of the compiler, a console window must be launched using the Windows Start Menu (choices: Start, All Programs, Accessories, Command Prompt). The new console window that appears will display a system prompting message such as "C:\Documents and Settings\Owner>". The user would then use whatever character-based commands were necessary to locate and execute the .exe file containing their program. When the program begins execution, the console window should clear (go blank) and the cursor should be positioned in the home (upper-left) corner of the window prior to any output being produced.

PATH: Instructional Server> COP 2000> Examples>