DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to clear screen in C++?

In this article we will discuss the method of clearing the screen or console display. There are more than one method of clearing the console but in this article we discussed only the general ones.


title: "How to clear screen in C++?"
tags: cpp

canonical_url: https://kodlogs.com/blog/881/how-to-clear-screen-in-c

Methods

  • Using function system()
  • Creating new lines
  • Using ##system()

The simplest method of clearing the screen is using the function system(). While it is so simple it has some disadvantages.
It is resource heavy.
It defeats security.
Anti-virus programs hate it.

#include <iostream>
#include <stdlib.h>
int main()
{
system("CLS");
cout << "Hello"<<flush;
system("CLS");
cout<<"Hello again"<<endl;
return 0;
}
Enter fullscreen mode Exit fullscreen mode

Note: If you want to clear the screen after cout statement, you have to use flush.
Flush forces the printing to the screen before clearing the screen

Creating new line

This method is stirring (pathetic) but it can be used. By creating so many new lines the console looks clean but it can be slow.

#include <iostream>
#include <string>

void clearscreen()
{ cout << string( 100, '\n' );
}
 #include <stdio.h>

  void ClearScreen()
    {
    int n;
    for (n = 0; n < 10; n++)
      printf( "\n\n\n\n\n\n\n\n\n\n" );
    }
Enter fullscreen mode Exit fullscreen mode

Using

The conio header file is so much popular. It provides the function clrscr() to clear the screen.

#include <conio.h>
#include <stdio.h>
#include <string.h>

int main()
  {
  char users_name[ 100 ];

  printf( "What is your name> " );
  fgets( users_name, sizeof( users_name ), stdin );
  *strchr( users_name, '\n' ) = '\0';

  /* Here is where we clear the screen */
  clrscr();

  printf( "Greetings and salutations %s!\n", users_name );

  printf( "\n\n\nPress ENTER to quit." );
  fgets( users_name, sizeof( users_name ), stdin );

  return 0;
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dynamicsquid profile image
DynamicSquid

I think conio.h is only for windows though