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
Example
The system(“cls”) function is called to clear the code after execution:
#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.