How can I clear console

2019-01-02 23:42发布

As in the title. How can I clear console in C++?

18条回答
来,给爷笑一个
2楼-- · 2019-01-03 00:11

Use system("cls") to clear the screen:

#include <stdlib.h>

int main(void)
{
    system("cls");
    return 0;
}
查看更多
看我几分像从前
3楼-- · 2019-01-03 00:13

For pure C++

You can't. C++ doesn't even have the concept of a console.

The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.

See this entry in the comp.lang.c++ FAQ:

OS-Specific

If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.

For Windows (as in your tag), check out this link:

Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.

Libraries (somewhat portable)

ncurses is a library that supports console manipulation:

查看更多
疯言疯语
4楼-- · 2019-01-03 00:16

For Linux/Unix and maybe some others but not for Windows before 10 TH2:

printf("\033c");

will reset terminal.

查看更多
等我变得足够好
5楼-- · 2019-01-03 00:19
// #define _WIN32_WINNT 0x0500     // windows >= 2000 
#include <windows.h> 
#include <iostream>

using namespace std; 

void pos(short C, short R)
{
    COORD xy ;
    xy.X = C ;
    xy.Y = R ;
    SetConsoleCursorPosition( 
    GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void cls( )
{
    pos(0,0);
    for(int j=0;j<100;j++)
    cout << string(100, ' ');
    pos(0,0);
} 

int main( void )
{
    // write somthing and wait 
    for(int j=0;j<100;j++)
    cout << string(10, 'a');
    cout << "\n\npress any key to cls... ";
    cin.get();

    // clean the screen
    cls();

    return 0;
}
查看更多
Explosion°爆炸
6楼-- · 2019-01-03 00:20

edit: completely redone question

Simply test what system they are on and send a system command depending on the system. though this will be set at compile time

#ifdef __WIN32
    system("cls");
#else
    system("clear"); // most other systems use this
#endif

This is a completely new method!

查看更多
太酷不给撩
7楼-- · 2019-01-03 00:21

The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.

int main(int argc, char *argv)
{
  for(int i = 0; i <1024*1024; i++)
      std::cout << ' ' << std::endl;

  return 0;
}

The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.

查看更多
登录 后发表回答