How do I clear the console in BOTH Windows and Linux using C++

前端 未结 12 1477
我寻月下人不归
我寻月下人不归 2020-11-30 01:54

I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don\'t want

相关标签:
12条回答
  • 2020-11-30 02:31

    Wouldn't

    for (int i=0;i<1000;i++){cout<<endl;}
    

    clear the screen in all OSes?

    0 讨论(0)
  • 2020-11-30 02:32

    This should work if you're working on console

    #include <conio.h>
    
    int main()
    
    {
        clrscr();
    }
    
    0 讨论(0)
  • 2020-11-30 02:37

    Short answer: you can't.

    Longer answer: Use a curses library (ncurses on Unix, pdcurses on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows).

    Most difficult answer: Use #ifdef _WIN32 and stuff like that to make your code act differently on different operating systems.

    0 讨论(0)
  • 2020-11-30 02:38

    A simple trick: Why not checking the OS type by using macros in combination with using the system() command for clearing the console? This way, you are going to execute a system command with the appropriate console command as parameter.

    #ifdef _WIN32
    #define CLEAR "cls"
    #else //In any other OS
    #define CLEAR "clear"
    #endif
    
    //And in the point you want to clear the screen:
    //....
    system(CLEAR);
    //....
    
    0 讨论(0)
  • 2020-11-30 02:38

    The question as posted is unanswerable, because it imposes impossible restrictions. "Clearing the screen" is a very different action across different operating systems, and how one does it is operating system specific. See this Frequently Given Answer for a full explanation of how to do it on several popular platforms with "consoles" and platforms with "terminals". You'll also find in the same place some explanation of the common mistakes to avoid, several of which are — alas! — given above as answers.

    0 讨论(0)
  • 2020-11-30 02:39

    On linux it's possible to clear the console. The finest way is to write the following escape sequence to stdout:

    write(1,"\E[H\E[2J",7);
    

    which is what /usr/bin/clear does, without the overhead of creating another process.

    0 讨论(0)
提交回复
热议问题