C++

How to Clear the Console in C++

The console window in C++ displays the output of the code written in the command window. If the console window is not cleared after getting the output, then on the execution of code next time, there will be a prefilled window to show the output, which may cause inconvenience while reading the output. To clear the console window for the user’s convenience, the system(“cls”) is used in C++.

Clear Console Window Using System(“cls”) in C++

In the stdlib header file there is a predefined function system(“cls”) , when this function is called it returns the clear blank console window. Preferably, this function is called in the beginning of the code to make sure the console window is blank, but it can also be called anywhere else in the code.

Syntax

// Header Files

 

main()
{
    system("cls");
    statement 2;
    statement 3;
    .
    .
}

Example

The system(“cls”) function is called to clear the code after execution:

#include <iostream>

#include <stdlib.h>

#include<conio.h>

using namespace std;

int main() {

    int num;

    cout << "Enter an integer: ";

    cin >> num;// Taking input

    cout << "The number is: " << num;

  getch();

    // Calling system function and passing cls as argument

    system("cls");

    cout << "The screen has been cleared!";

    return 0;

}

The user is asked to input an integer, which is shown at the output. To read input from the console, the getch() function is declared in the conio.h header file. It can read only one input at a time, when a keyboard key is pressed to execute this function. Here, any of the keys is pressed, to enable the clear screen operation:

The user enters an integer 54 which is displayed at the output:

After getting the output, any key of the keyboard is pressed to clear the console window.

Conclusion

In the stdlib header file there is a predefined function system(“cls”), when this function is called it returns the clear blank console window. Preferably, this function is called in the beginning of the code to make sure the console window is blank, but it can also be called anywhere else in the code. This makes the user not face an already filled console window and the user can read glitch free output.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.