如何清除 C 语言中的控制台屏幕?

发布于 2024-08-22 19:33:27 字数 53 浏览 4 评论 0原文

除了使用 system("cls") 之外,还有“正确”的方法来清除 C 中的控制台窗口吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

梅窗月明清似水 2024-08-29 19:33:27
printf("\e[1;1H\e[2J");

该功能将在 ANSI 终端上运行,需要 POSIX。我假设有一个版本也可以在 Windows 控制台上工作,因为它也支持 ANSI 转义序列。

#include <unistd.h>

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

还有一些其他的
替代方案,其中一些不会将光标移动到 {1,1}。

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}.

秋风の叶未落 2024-08-29 19:33:27

嗯,C 不理解屏幕的概念。所以任何代码都无法移植。也许看看 conio.h
curses,根据您的需要?

无论使用什么库,可移植性都是一个问题。

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.

一个人的旅程 2024-08-29 19:33:27

为了可移植性,请尝试以下操作:

#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif

然后只需调用 clrscr() 即可。在 Windows 上,它将使用 conio.hclrscr(),在 Linux 上,它将使用 ANSI 转义码。

如果您真的想“正确”地做到这一点,您可以消除中间人(conioprintf等),然后只需低级系统工具(准备大量代码转储):

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void ClearScreen()
{
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
}

#else // !_WIN32
#include <unistd.h>
#include <term.h>

void ClearScreen()
{
  if (!cur_term)
  {
     int result;
     setupterm( NULL, STDOUT_FILENO, &result );
     if (result <= 0) return;
  }

   putp( tigetstr( "clear" ) );
}
#endif

For portability, try this:

#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif

Then simply call clrscr(). On Windows, it will use conio.h's clrscr(), and on Linux, it will use ANSI escape codes.

If you really want to do it "properly", you can eliminate the middlemen (conio, printf, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void ClearScreen()
{
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
}

#else // !_WIN32
#include <unistd.h>
#include <term.h>

void ClearScreen()
{
  if (!cur_term)
  {
     int result;
     setupterm( NULL, STDOUT_FILENO, &result );
     if (result <= 0) return;
  }

   putp( tigetstr( "clear" ) );
}
#endif
找个人就嫁了吧 2024-08-29 19:33:27

在 Windows(cmd.exe)、Linux(Bash 和 zsh)和 OS X(zsh) 上测试的解决方法:

#include <stdlib.h>

void clrscr()
{
    system("@cls||clear");
}

A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):

#include <stdlib.h>

void clrscr()
{
    system("@cls||clear");
}
淡看悲欢离合 2024-08-29 19:33:27

使用宏,您可以检查您是否使用 Windows、Linux、Mac 还是 Unix,并根据当前平台调用相应的函数。事情如下:

void clear(){
    #if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
        system("clear");
    #endif

    #if defined(_WIN32) || defined(_WIN64)
        system("cls");
    #endif
}

Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:

void clear(){
    #if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
        system("clear");
    #endif

    #if defined(_WIN32) || defined(_WIN64)
        system("cls");
    #endif
}
同尘 2024-08-29 19:33:27

既然您提到了 cls,听起来您指的是 Windows。如果是这样,则此知识库项目具有执行此操作的代码。我刚刚尝试了一下,当我使用以下代码调用它时,它起作用了:

cls( GetStdHandle( STD_OUTPUT_HANDLE ));

Since you mention cls, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:

cls( GetStdHandle( STD_OUTPUT_HANDLE ));
我乃一代侩神 2024-08-29 19:33:27
#include <conio.h>

并使用

clrscr()
#include <conio.h>

and use

clrscr()
妖妓 2024-08-29 19:33:27

Windows:

system("cls");

Unix:

system("clear");

您可以改为插入换行符,直到所有内容都滚动,看看 此处

这样,您就可以轻松实现可移植性。

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.

零度℉ 2024-08-29 19:33:27

没有可移植的 C 方法可以做到这一点。尽管各种光标操作库(例如curses)相对可移植。 conio.h 可在 OS/2 DOS 和 Windows 之间移植,但不能移植到 *nix变种。

“控制台”的整个概念是标准 C 范围之外的概念。

如果您正在寻找纯 Win32 API 解决方案,Windows 控制台 API 中没有单个调用可以执行此操作。一种方法是 FillConsoleOutputCharacter 足够大字符数。或者 WriteConsoleOutput 您可以使用 GetConsoleScreenBufferInfo 找出多少个字符就足够了。

您还可以创建一个全新的控制台屏幕缓冲区并制作当前的。

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 current one.

北渚 2024-08-29 19:33:27

只需输入 clrscr();函数在 void main() 中。

例如:

void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}

clrscr();

轻松清屏功能。

just type clrscr(); function in void main().

as example:

void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}

clrscr();

function easy to clear screen.

在你怀里撒娇 2024-08-29 19:33:27

在 Windows 中我犯了使用错误

system("clear")

,但这实际上是针对 Linux 的

Windows 类型

system("cls")

没有 #include conio.h

In Windows I have made the mistake of using

system("clear")

but that is actually for Linux

The Windows type is

system("cls")

without #include conio.h

一身骄傲 2024-08-29 19:33:27

正确的方法是使用 tput 或 terminfo 函数获取终端属性,然后根据维度插入换行符。

The proper way to do it is by using tput or terminfo functions to obtain terminal properties and then insert newlines according to the dimensions..

纵性 2024-08-29 19:33:27

这应该有效。然后只需调用 cls();每当您想清除屏幕时。

(使用之前建议的方法。)

#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");
    }
}

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");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文