English 中文(简体)
在C语言中,如何清空控制台屏幕?
原标题:How do you clear the console screen in C?

除了使用system("cls"),在C中有没有“正确”的清除控制台窗口的方法?

最佳回答

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?

无论使用哪个库,移植性都是个问题。

问题回答
printf("e[1;1He[2J");

这项职能将在ANSI终端站运作,需要PPOSIX。 我假设有一个版本,也可在窗.上工作,因为它也支持ANSI的逃脱顺序。

#include <unistd.h>

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

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

为了便携性,请试试这个:

#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("e[1;1He[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

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

#include <stdlib.h>

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

使用宏,你可以检查你是在Windows、Linux、Mac还是Unix上,并根据当前平台调用相应的函数。具体如下:

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

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

既然您提到了cls,那么您应该指的是Windows。如果是这样,这篇KB文章中有一段代码可以实现。我刚刚试过,当我使用以下代码调用它时,它可以正常工作:

cls( GetStdHandle( STD_OUTPUT_HANDLE ));
#include <conio.h>

和使用 Translation: "和使用" means "and use" in English.

clrscr()

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

“游戏机”的整个概念超出了标准C的范围。”

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

您也可以创建全新的控制台屏幕缓冲区,并将其设置为当前屏幕缓冲区。

Windows: 窗户

系统(“cls”);

Unix:

system("clear"); 的翻译为: system("clear");

那么,在一切照搬之前,你可以插入新的线果园,看here

有了它,你很容易实现可携带性。

在void main()中键入clrscr();函数。

作为例子:

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

clrscr();

易于清除屏幕。

在Windows系统中,我犯了错误,使用了…… (The sentence is not complete, please provide the complete sentence for an accurate translation.)

system("clear")

但是,这实际上是对六氯环己烷而言。

"窗口类型"

system("cls")

没有 #include conio.h

正确的做法是使用tputterminfo函数获取终端属性,然后根据维度插入新行。

只需调用下面的函数:

void clearScreen() {
    system("clear");
}




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...