How do you clear the console screen in C?

2019-01-05 01:16发布

Is there a "proper" way to clear the console window in C, besides using system("cls")?

12条回答
做自己的国王
2楼-- · 2019-01-05 01:18

There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.

The entire notion of a "console" is a concept outside of the scope of standard C.

If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.

You can also create an entirely new Console Screen Buffer and make the the current one.

查看更多
叼着烟拽天下
3楼-- · 2019-01-05 01:24
printf("\e[1;1H\e[2J");

This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.

#include <unistd.h>

void clearScreen()
{
  const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
  write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}

There are some other alternatives, some of which don't move the cursor to {1,1}.

查看更多
对你真心纯属浪费
4楼-- · 2019-01-05 01:28

Windows:

system("cls");

Unix:

system("clear");

You could instead, insert newline chars until everything gets scrolled, take a look here.

With that, you achieve portability easily.

查看更多
▲ chillily
5楼-- · 2019-01-05 01:32

Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or curses, according to your needs?

Portability is an issue, no matter what library is used.

查看更多
Deceive 欺骗
6楼-- · 2019-01-05 01:32

This should work. Then just call cls(); whenever you want to clear the screen.

(using the method suggested before.)

#include <stdio.h>
void cls()
{
    int x;
    for ( x = 0; x < 10; x++ ) 
    {
        printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    }
}
查看更多
beautiful°
7楼-- · 2019-01-05 01:34
#include <conio.h>

and use

clrscr()
查看更多
登录 后发表回答