When writing some console app, we sometimes have requirements to interactive with the console screen directly. One example is clearing the console screen.
In this article, you will learn how to clear the console screen properly in C++ code.
To clear the console screen, one of the approach is directly using the system console command:
Yeah… It works. However, there are some problems.
- Running an external application cost a lot of system resources. If you need to clear the console screen frequently, maybe one time per second or even higher, you’d better try other ways.
- This approach depends on the OS. If you are writing some cross-platform program, you have to use some macro tricks to workaround it. And if you are writing a program for some special Linux platform, the
clearcommand could just unavailable, which can break your program.
Fortunately, almost all terminals now follow a standard. Which allow us to have a universal way to clear the console.
In this approach, the first escape code
\033[2J can clear the screen, and the second escape code
\033[1;1H can move the cursor to (1,1).
This approach is only available on Windows! If you have the requirement to target to Linux/UN*X system, just use the previous code directly.
Although the previous example work well on Windows, there is one obvious shortcoming: after clearing the screen, you can still see the scrollbar exist, and if you scroll up, you can see the old log is still there.
Unfortunately, to resolve this problem, we have to use a native approach.