Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing the Console in C++

Tags:

c++

I am trying to clear the console in C++. I know printing a number of newlines is a bad practice, as it can be slow and is not always reliable to completely clear the console window, but I have researched multiple options and have found almost no other solutions besides system("cls"), which is an even worse option.

Essentially, I have used the line cout << string(100, '\n'); but I am getting a near-unidentifiable error when I try to run the program.

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

I have also researched this, and found that most explanations were too complicated for me as a beginning C++ programmer to understand, or completely unrelated to my problem.

My questions are (1) is there a way to fix this error, and (2) could there be a better, cross-platform way of clearing the console other than printing 100 newlines?

I also heard of Console.clear(), but I'm unsure if this is cross-platform. From what I've seen, it looks more like a Windows command. I've also heard of the curses library, which I was willing to research and use, until I read somewhere that it was not recommended to use the functions which I am familiar with coupled with the curses library functions.

Thank you in advance!

like image 466
Abluescarab Avatar asked Jun 02 '26 16:06

Abluescarab


1 Answers

About your error... you have to...

#include <iostream> 
#include <string>

using namespace std;

If you are using just windows use windows console API. If you are using a linux\unix terminal, use escape codes. You can do a #if to choose between the two methods.

On linux\unix use the write function defined in in this way:

write(1,"\E[H\E[2J",7); // we use ANSI escape sequences here.

Here is the microsoft page that explain how to do that.

http://support.microsoft.com/kb/99261

The really bad console api microsoft use for the console always makes me angry :) why 100 lines of code to clear a screen? :)

Now the if... you should create a clearscreen.h file and a clearscreen.cpp file.

In clearscreen.h we just put our function.

 void clearconsole();

In clearscreen.cpp we put our code for both operative systems

#ifdef _WIN32 || _WIN64

    #include <windows.h>

    void clearconsole()
    {
        ...
        // 100 lines of codes copied from microsoft article
    }

#else

    #include <unistd.h>

    void clearconsole()
    {
        write(1,"\E[H\E[2J",7);
    }

#endif
like image 52
Salvatore Previti Avatar answered Jun 05 '26 08:06

Salvatore Previti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!