Clear the screen

Pages: 12
This short article describes the method of clearing the console display of all text and positioning the text cursor in the home location (the upper-left corner).

Before becoming too comfortable doing this kind of thing blithely, make sure you read and understand Types and purposes of console applications.


- - - - - - - - - - - - - - - - The Simple Answer - - - - - - - - - - - - - - - -

While simple, it really is a Bad Thing. See Why system() is evil for more.
1
2
3
4
5
6
7
#ifdef __cplusplus__
  #include <cstdlib>
#else
  #include <stdlib.h>
#endif

if (system("CLS")) system("clear");



- - - - - - - - - - - - - - - - The Standard Way - - - - - - - - - - - - - - - -

Pathetic, but passing, and usually correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifdef __cplusplus__

  #include <iostream>
  #include <string>

  void ClearScreen()
    {
    cout << string( 100, '\n' );
    }

#else

  #include <stdio.h>

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

#endif 

This works, of course, just by putting a hundred newlines to the display. Over a poorly-buffered network connection, this might be s l o w. Alas.


- - - - - - - - - - - - - - - - Using NCurses - - - - - - - - - - - - - - - -

The Curses library is designed for working with the console. Advantages: it is cross-platform. Disadvantages: it doesn't interact well with the standard streams. In other words, you shouldn't mix printf(), etc or cout, etc with curses. Use one or the other, not both.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <curses.h>

int main()
  {
  char users_name[ 100 ];

  initscr();
  (void)echo();

  addstr( "What is your name> " );
  refresh();
  getnstr( users_name, sizeof( users_name ) - 1 );

  clear();

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

  printw( "\n\n\nPress ENTER to quit." );
  refresh();
  getnstr( users_name, sizeof( users_name ) - 1 );

  endwin();
  return 0;
  }  

Again, if all you want to do is clear the screen on occasion then using Curses is complete overkill.


- - - - - - - - - - - - - - - - Using <conio.h> - - - - - - - - - - - - - - - -

This library is severely deprecated, but it is so popular that some form of it exists on most 80x86 hardware compilers --almost always on Windows compilers, and there exist Linux versions too. However, given the choice, use NCurses instead...

The caveat is that it is non-standard, meaning that the actual functions it provides vary a lot and they don't always behave just right. Hence, for anything other than Windows programs it is also a sub-optimal solution. See Using <conio.h> for more.

If undaunted, then here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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';

  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;
  }

Now, the enterprising among you may have tried to compile this. If it worked for you, you're lucky. If not, then you have learned firsthand the shortcomings of the <conio.h> library. Alas.
Last edited on
- - - - - - - - - - - - - - - - OS-specific ways - - - - - - - - - - - - - - - -

So, on to the part for those of us who have the hack nature.

Windows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <windows.h>

void ClearScreen()
  {
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
  }

POSIX (Unix, Linux, Mac OSX, etc)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <unistd.h>
#include <term.h>

void ClearScreen()
  {
  if (!cur_term)
    {
    int result;
    setupterm( NULL, STDOUT_FILENO, &result );
    if (result <= 0) return;
    }

  putp( tigetstr( "clear" ) );
  }

You'll have to link to the proper library (one of -lcurses, -lterminfo, etc) to compile that last one.

Until next time!
Last edited on
hello, We use clear screen for clear console woindow..
We use clrscr(); for clear screen.
But 1stly we add its header file, which is conio.h ..
like
#include<iostream.h>
#include<conio.h>

void main()

{
clrscr();
cout<<"Waw screen is clear";
getch();
}

If yoe are not include conio.h then its creat an error..

i make 1 very wonderful code for all new comers n youngers...

// For All new Comers Student....

#include<iostream.h>
#include<conio.h> // We use conio to get output on console secreen..
// Its also use for Clear screen
#include<stdlib.h> // use for exit();
void main()
{
clrscr(); //---> Must be put on start:P..

int op;
int n1,n2;
while(1) // use for infinite n 5 for exit.
{
clrscr(); // --->> This clr scr use for clear screen on every keys u enter..
cout<<"Enter 1 for addition.. "<<endl;
cout<<"Enter 2 for Subtraction.. "<<endl;
cout<<"Enter 3 for multiplication.. "<<endl;
cout<<"Enter 4 for division.. "<<endl;
cout<<"Enter 5 for Exit.. "<<endl;
op=getche(); // u get chracter instead of integer so loop not b infinite
cout<<endl;
switch(op) // ye use switch or if else conditional staement..
{
case '1':
cout<<"Enter n1: "; cin>>n1;
cout<<"Enter n2: "; cin>>n2;
cout<<"Additin answer is: "<<n1+n2<<endl;
getch();
break;
case '2':
cout<<"Enter n1: "; cin>>n1;
cout<<"Enter n2: "; cin>>n2;
if(n1>n2)
{
cout<<"Subtraction answer is: "<<n1-n2<<endl;
getch();
}
else
{
cout<<"Subtraction answer is: "<<n2-n1<<endl;
getch();
}
break;
case '3':
cout<<"Enter n1: "; cin>>n1;
cout<<"Enter n2: "; cin>>n2;
cout<<"Multiplication answer is: "<<n1*n2;
getch();
break;
case '4':
cout<<"Enter n1: "; cin>>n1;
cout<<"Enter n2: "; cin>>n2;
if(n1>n2)
{
cout<<"Division answer is: "<<n1/n2<<endl;
getch();
}
else
{
cout<<"Divison answer is: "<<n2/n1<<endl;
getch();
}
break;
case '5':
cout<<"Program is Exit..";
getch(); //use getch or delay..
exit(1); // is just read 1 above state ment
// if u put 2 instead of 1, then its print above 2 statement..
break;
}
}
getch();
}



For more contact: habibraza@msn.com
closed account (z05DSL3A)
mmlb, conio.h is not a good way to go, it is non standard and varies significantly from compiler to compiler.
The first example code that you posted:
1
2
3
4
5
6
7
8
9
10
#include<iostream.h>
#include<conio.h>

void main()

{
clrscr();
cout<<"Waw screen is clear";
getch();
}

will not even compile with MS C++.
Last edited on
Heh heh heh... I think it amazing the amount of spam threads like this attract.
ahan grey wolf:P.. Well its example of Borland C..
We no need to include conio.h in MS C++..
Quit dinking with nonstandard stuff.

If you must clear the screen, then why not just use the proper Windows or POSIX functions I gave you?
http://www.cplusplus.com/forum/articles/10515/page1.html#msg49080

The whole point of this thread is how to do things the Right Way; it is not "Every possible variation of how to do things the Wrong Way".
Hello, everyone! I'm a beginner like some around here and this is in fact my first post. I have read that some Visual C++ 2005 or 2008 users couldn't use: system ("cls") to clear the screen besides I've heard it's a bad habit. I have Visual 2005 and what I do is writing this piece of code:

System::Console::Clear();

I use it cus doing so I avoid putting some extra code or including header files and such. But as I said before I'm a complete beginner and I want to know if it's also a bad practice??
That thar must be .net

Not really part of standard C++. It's fine if you're developing .net programs though.
It should be pointed out that "The Standard Way" does not position the cursor in the upper-left corner, so it doesn't quite do the same job as the others.
Hi, in this my first post ... my question is : Why not use the ANSI Terminal escapes controls ? just like "033]" and follow ? Look this snippet code :

printf("\033[2J"); // from <stdio.h>

thanks.
Last edited on
Because not all terminals accept ANSI terminal escape codes. (DOS, remember, requires you to load ANSI.SYS just to use a small subset of the ANSI/VT100+ codes.)

On Windows, clear it the Windows way.

On POSIX systems (Unix/Linux/etc), use the terminfo database like I showed you to output the correct terminal control sequence. (Which might very well be "\033[2J" if your program is running on a VT100+ compatible terminal/emulator, like xterm.)

The difference is that when you use the function I gave you, your programs will work on any terminal listed in the terminfo database, but if you just dump terminal codes you 1) bind yourself to a specific subset of terminal/emulators, and 2) introduce nasty surprises when fancy control sequences aren't emitted like you wrote them.
http://www.cplusplus.com/forum/articles/10515/page1.html#msg49080

Hope this helps.
This is not quite on topic and im sure that if i looked i could find a thread that covers this but why do you people (mmlb) insist on using void main(). It makes no sense with expected return values.
It's because they fail and compilers sometimes support so they can keep supporting "legacy" code.
Well that seems like the lazy way to avoid errors with returns but i'll have to look into 'legacy' code. i assume that it is old code using void main(), but...
Actually the standard says that you can't EVER use void main() but some old compilers let you and now everyone "has" to support that...(they shouldn't IMO).
Last edited on
The standard allows main() not to return anything even if it does have int as its return type, so considering there can be only one main(), I don't think it makes much sense for compilers to allow void main().
Last edited on
@ firedraco: that's what i thought
@helios: I always wondered, when a program's entry point returns something, where does it return it to?
That's system-dependent.
All OSs I know of pass the return value to the shell so scripts can use it to determine the result of the program.
Pages: 12