How do I clear the screen?

Duoas 0 Tallied Votes 447 Views Share

First off, C++ does not know anything about the I/O device you are using. It can be a keyboard and monitor, or a file, or a network connection, or anything which can do I/O. What that means is that there is no standard way to do this in C++.

That said, the following should work on any Unix/Linux platform and on any version of Windows. That's because it cheats by using another program to clear the screen.

All Unix/Linux systems have a command line program called "clear" which clears the screen.
Likewise, all Windows systems have a command line command called "cls" to do the same.

This works by first trying one, and if that doesn't work, then using the other. The order in which they are tried does not matter.

#include <iostream>
#include <cstdlib>  // system()

void clearscreen() {
  if (system( "clear" )) system( "cls" );
  }

int main() {
  // Clear the screen and  print a friendly message
  clearscreen();
  std::cout << "Hello world!\n";

  // Wait for the user to press the enter key
  std::cout << "Press ENTER to continue...";
  while (std::cin.get() != '\n');

  return EXIT_SUCCESS;
  }
munyu 0 Newbie Poster

im quiet impressed thats a nice and simple function

Duoas 1,025 Postaholic Featured Poster

Keep in mind that this is useful only for homework problems or other simple software.

If you are writing commercial software, or secure systems, you should know better than to use this, as it is resource heavy and it is a huge, gaping security hole.

Perhaps I should post an update for how to do this the Right Way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.