How do I clear the console in BOTH Windows and Lin

2019-01-07 09:49发布

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 the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).

12条回答
Lonely孤独者°
2楼-- · 2019-01-07 10:28

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.

查看更多
干净又极端
3楼-- · 2019-01-07 10:28

Well there is a very close alternative to clearing the screen. You could try using a for loop that repeats new lines a lot. For example:

for (i = 0; i < 100000; i++)
{
  printf ("\n\n\n\n\n");
}

After you do this loop the terminal wan't allow you to scroll back to where you were at the top, an unprofessional approach with common sense pretty much. It does not directly answer what you are asking but it can work.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-07 10:32

This should work if you're working on console

#include <conio.h>

int main()

{
    clrscr();
}
查看更多
Anthone
5楼-- · 2019-01-07 10:33

Short answer

void cls(void)
{
    system("cls||clear");
    return;
}

Long answer, please read:

system("pause") clarification

查看更多
The star\"
6楼-- · 2019-01-07 10:35

I know this isn't answering my own question but! This works for Windows (#include <windows.h>):

void clrscr()
{
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coord = {0, 0};
    DWORD count;

    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdOut, &csbi);

    FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

    SetConsoleCursorPosition(hStdOut, coord);
}
查看更多
对你真心纯属浪费
7楼-- · 2019-01-07 10:37

Wouldn't

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

clear the screen in all OSes?

查看更多
登录 后发表回答