C++ 如何清除控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6486289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I clear console
提问by Thomas B
As in the title. How can I clear console in C++?
如标题所示。如何清除 C++ 中的控制台?
回答by Merlyn Morgan-Graham
For pure C++
对于纯 C++
You can't. C++ doesn't even have the concept of a console.
你不能。C++ 甚至没有控制台的概念。
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.
该程序可以打印到打印机,直接输出到文件,或者被重定向到另一个程序的输入,因为它所关心的一切。即使您可以在 C++ 中清除控制台,它也会使这些情况变得更加混乱。
See this entry in the comp.lang.c++ FAQ:
请参阅 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:
对于 Windows(如您的标签中所示),请查看此链接:
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.
编辑:之前提到的这个答案使用system("cls");
,因为微软说要这样做。然而,评论中已经指出,这不是一件安全的事情。由于这个问题,我删除了 Microsoft 文章的链接。
Libraries (somewhat portable)
图书馆(有点便携)
ncurses is a library that supports console manipulation:
ncurses 是一个支持控制台操作的库:
- http://www.gnu.org/software/ncurses/(runs on Posix systems)
- http://gnuwin32.sourceforge.net/packages/ncurses.htm(somewhat old Windows port)
- http://www.gnu.org/software/ncurses/(在 Posix 系统上运行)
- http://gnuwin32.sourceforge.net/packages/ncurses.htm(有点旧的 Windows 端口)
回答by Cat Plus Plus
For Windows, via Console API:
对于 Windows,通过控制台 API:
void clear() {
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
}
It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls")
handles errors any better.
它愉快地忽略了所有可能的错误,但是嘿,这是控制台清除。不像system("cls")
处理错误更好。
For *nixes, you usually can go with ANSI escape codes, so it'd be:
对于 *nixes,你通常可以使用 ANSI 转义码,所以它是:
void clear() {
// CSI[2J clears screen, CSI[H moves the cursor to top-left corner
std::cout << "\x1B[2J\x1B[H";
}
Using system
for this is just ugly.
使用system
了这仅仅是丑陋的。
回答by NoAngel
For Linux/Unix and maybe some others but not for Windows before 10 TH2:
对于 Linux/Unix 和其他一些,但不适用于 10 TH2 之前的 Windows:
printf("3c");
will reset terminal.
将重置终端。
回答by Joma
The easiest way for me without having to reinvent the wheel.
对我来说最简单的方法而不必重新发明轮子。
void Clear()
{
#if defined _WIN32
system("cls");
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
#elif defined (__APPLE__)
system("clear");
#endif
}
回答by Swift - Friday Pie
outputting multiple lines to window console is useless..it just adds empty lines to it. sadly, way is windows specific and involves either conio.h (and clrscr() may not exist, that's not a standard header either) or Win API method
将多行输出到窗口控制台是没有用的..它只是添加了空行。遗憾的是,方式是特定于 Windows 的,涉及 conio.h(并且 clrscr() 可能不存在,这也不是标准头文件)或 Win API 方法
#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 );
}
For POSIX system it's way simpler, you may use ncurses or terminal functions
对于 POSIX 系统,它更简单,您可以使用 ncurses 或终端功能
#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" ) );
}
回答by Firefox_
// #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;
}
回答by LoveToCode
In Windows:
在 Windows 中:
#include <cstdlib>
int main() {
std::system("cls");
return 0;
}
In Linux/Unix:
在 Linux/Unix 中:
#include <cstdlib>
int main() {
std::system("clear");
return 0;
}
回答by user3179329
To clear the screen you will first need to include a module:
要清除屏幕,您首先需要包含一个模块:
#include <stdlib.h>
this will import windows commands. Then you can use the 'system' function to run Batch commands (which edit the console). On Windows in C++, the command to clear the screen would be:
这将导入 Windows 命令。然后您可以使用“系统”功能运行批处理命令(编辑控制台)。在 C++ 的 Windows 上,清除屏幕的命令是:
system("CLS");
And that would clear the console. The entire code would look like this:
这将清除控制台。整个代码如下所示:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
system("CLS");
}
And that's all you need! Goodluck :)
这就是你所需要的!祝你好运 :)
回答by Wesam
Use system("cls")
to clear the screen:
使用system("cls")
清除屏幕:
#include <stdlib.h>
int main(void)
{
system("cls");
return 0;
}
回答by Max Goddard
This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.
这在 MAC 上很难做到,因为它无法访问可以帮助清除屏幕的 Windows 功能。我最好的解决方法是循环并添加行,直到终端清晰,然后运行程序。但是,如果您主要和经常使用它,那么这不是那么有效或内存友好。
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}