Link to home
Start Free TrialLog in
Avatar of browerjason
browerjason

asked on

How to clear screen in console application

I have taken several intro to programming classes like Java, C and C++.  I have had to develop many console applications since I started these courses.  The one thing that I always hated was, that after I asked a few questions from the user, the screen would just continue to scroll like at a unix command prompt when typing many commands.  I want to be able to clear the screen on command.  How can I do this?? What is the function and what header file is it located in??


Jason
Avatar of wataru
wataru

Try this

putchar (14); // clear screen
putchar (7); // beep
I think that clear the screen is depending of the OS, but if the OS is compliant with ANSI standard, try to write to console the scape secuence the command for clear the screen:
printf( "\33[2J"); // Example in C/C++
// "\33" is the scape caracter (0x1b)
If your OS is DOS/WINDOWS, you must to load in your config.sys the ansi.sys driver for make your OS an ANSI compliant.
wataru changed the proposed answer to a comment
C++ provides no mechanism for this.   C++ is OS and hardware independant.  So C++ does not even assume there is a screen, much less that it can be cleared (C++ might be ouputting to a teletype, and you can't clear a teletype.)

However, there are OS-specifc and hardware specific wasy to do this.  But you haven't told us the OS or hardware you are using.

For example in windows you can use:

From
http://support.microsoft.com/support/kb/articles/q99/2/61.asp

/* Standard error macro for reporting API errors */
   #define PERR(bSuccess, api){if(!(bSuccess)) printf("%s:Error %d from %s \
      on line %d\n", __FILE__, GetLastError(), api, __LINE__);}

   void cls( HANDLE hConsole )
   {
      COORD coordScreen = { 0, 0 };    /* here's where we'll home the
                                          cursor */
      BOOL bSuccess;
      DWORD cCharsWritten;
      CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
      DWORD dwConSize;                 /* number of character cells in
                                          the current buffer */

      /* get the number of character cells in the current buffer */

      bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
      PERR( bSuccess, "GetConsoleScreenBufferInfo" );
      dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

      /* fill the entire screen with blanks */

      bSuccess = FillConsoleOutputCharacter( hConsole, (TCHAR) ' ',
         dwConSize, coordScreen, &cCharsWritten );
      PERR( bSuccess, "FillConsoleOutputCharacter" );

      /* get the current text attribute */

      bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
      PERR( bSuccess, "ConsoleScreenBufferInfo" );

      /* now set the buffer's attributes accordingly */

      bSuccess = FillConsoleOutputAttribute( hConsole, csbi.wAttributes,
         dwConSize, coordScreen, &cCharsWritten );
      PERR( bSuccess, "FillConsoleOutputAttribute" );

      /* put the cursor at (0, 0) */

      bSuccess = SetConsoleCursorPosition( hConsole, coordScreen );
      PERR( bSuccess, "SetConsoleCursorPosition" );
      return;
   }
Since you're uing the term "console application" I'm asuming that you're using windows (since this is the term used by MSVC).
I would use the clrcsr() function (and include the conio.h file". This function is a DOS function but I think that MSVC has it too. (not sure).

Hope it helps,
Arnon David.
there is no clrscr() function in the VC library.  All non stadnard functions begin with an underscore, so it would be _clrscr(), but there isn't a _clrscr() either.   If this is for a win32 console, the best way would be to use the console API functions, as they are portable to other compilers.
ASKER CERTIFIED SOLUTION
Avatar of tdubroff
tdubroff

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That won't work on all computers.  "cls" is not universal--at all  More importantly it is a very very ineficient way to clear the screen.  That has to start a new process just to clear the screen.
True, but it is simply coded and will work on Windows PC's....and probably quite a few UNIX systems too.
simply coded?
ok, but as nietod commented, it create a new process.
I think that is a very high price for clearing the screen.
I still think that the ANSI sequence is the best way: very simple and very portable...
The ANSI method is not very portable anymore.  ANSI-compatible consoles are a thing of the past.  Almost all computers these days use graphical interfaces, even main-frames.  If you really need to support a lot of OSs that probably would be your best bet, but...I wouldn't want count on it.   I think I would prefer an OS-dependant method that is likely to be supported on the OS well into the future and without concern for hardware or compiler support.
Avatar of browerjason

ASKER

Answer accepted
Thanks,
     Your answer is the only one I could get to work on my Windows 98 system using Visual C++.  However, I am still interested in some of the other intelligent feedback I got on this question.

1)  One of you had mentioned to use the header file <conio.h> and the funtcion clrscr().  I saw this done in someone elses program on the net, but could not find that function in my header file.  This makes me wonder how the other person got this to work.

2)  I am also interested in the ANSI escape sequence that was mentioned.  I tried  "printf("\33[2]"); ", but my machine printed out "<- [2]" instead of clearing the screen.

I appreciate all the feedback.  I am now happy that I can clear the screen with the system("cls") method, but I am interested in some working alternative methods as well.

Thanks

Jason
You chose a very poor method.  Its increadibly inneficient--absurdly so.  You are litterlly suspending your program so another program (command.com) can be run.  That program then starts a second program (cls.exe) which forces command .com to be suspended.  then the screen is cleared, cls.exe ends.  Then command.com is resumed and exits.  Then your program resumes.  That is a heck of a lot of work, just to clear the screen!

>>  the funtcion clrscr().
I explain that was not standard.  VC doesn't include it.  It doesn't have to.

>>  I am also interested in the ANSI escape sequence
That is not standard either.  You can make it work if you have ansi.sys, but I woul;dn't recommend going that way unless you have to run onother platforms.  In that case it is your best bet, and it is very bad bet.

Did you try using the windows API functions?  If you are programming only for windows that would be the best way.  It is simple, fast, and standard (for windows).
No I didn't try the API functions because I am too new to be famialar with them.  The reason I chose the method that I did, was because it was the ONLY one that was suggested that worked.  Effeicency was not my immediate concern, solving the problem was.  If I knew how to use the API functions, then I would use them, but until then, the method that was suggested works great.

Thanks
I posted the code.  Copy it into your program and add

#include <windows.h>

to the top.  Then call cls() to clear the screen.
browerjason:
If you´re interested in the ANSI sequence, change the ']' for 'J', and load ansi.sys in your config.sys file.

nietod:
do you think this is not standard?
what´s the meaning of the 'S' of ANSI?
This sequence works on all VT terminal consoles, even I probed it in a small console of a computer in a car...
>>  all VT terminal consoles
That doesn't make it standard.  You can just write to video memory at the DOS video base address.  That works on all PCs,  Is that standard?  Its standard for a limited number of cases that choose to follow an uninforced standard.  For some concrete examples ANSI escape sequences, don't work on televideo terminals.  They don't work on Mac computers.  There is no ANSI.SYS type feature available to make them work.  They don't work on molecular consoles...   There probably 100s of other cases where they don't work.  They work in a relatively specific--and these days rare--case.
I've tried all of these methods and none of them have worked for me.  Anyone have any other ideas?
You could just:

int cls(void)
{
     gotoxy(1,1);

}
shoot
sorry!!

Stupid machine killed my code!

I really meant to say:

int cls(void)
{
    int x;
    gotoxy(1,1);
    for(x=0;x<80000;x++)
    {
          printf("   ");
    }
    gotoxy(1,1);
    return 1;
}

That should work. Although it does not clear the stdout (or stdin), it clears the console screen.

Thanx

Jonny K
(I may be a kid, but I'm a good programmer!)
// adapted from:
//    MSDN\Platform SDK\Reference\Code Sample\WINUI\CONSOLE\CONSOLE.C

void cls()
{
  COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
  DWORD cCharsWritten;
  CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
  DWORD dwConSize; /* number of character cells in the current buffer */
 
  /* get the output console handle */
  HANDLE hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
  /* get the number of character cells in the current buffer */
  GetConsoleScreenBufferInfo(hConsole, &csbi);
  dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
  /* fill the entire screen with blanks */
  FillConsoleOutputCharacter(hConsole, (TCHAR) ' ',
      dwConSize, coordScreen, &cCharsWritten);
  /* get the current text attribute */
  GetConsoleScreenBufferInfo(hConsole, &csbi);
  /* now set the buffer's attributes accordingly */
  FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
      dwConSize, coordScreen, &cCharsWritten);
  /* put the cursor at (0, 0) */
  SetConsoleCursorPosition(hConsole, coordScreen);
  return;
}
Anyone any ideas on how to close down the console window completely?

Im using nested loops and so break just doesnt work!