问题
As in the title. How can I clear console in C++?
回答1:
For pure C++
You can't. C++ doesn't even have the concept of a console.
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.
See this entry in the comp.lang.c++ FAQ:
- http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.20
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:
- How do we clear the console in assembly?
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.
Libraries (somewhat portable)
ncurses is a library that supports console manipulation:
- http://www.gnu.org/software/ncurses/ (runs on Posix systems)
- http://gnuwin32.sourceforge.net/packages/ncurses.htm (somewhat old Windows port)
回答2:
For Windows, via Console 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.
For *nixes, you usually can go with ANSI escape codes, so it'd be:
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.
回答3:
For Linux/Unix and maybe some others but not for Windows before 10 TH2:
printf("\033c");
will reset terminal.
回答4:
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
#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
#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" ) );
}
回答5:
// #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;
}
回答6:
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:
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 :)
回答7:
In Windows:
#include <cstdlib>
int main() {
std::system("cls");
return 0;
}
In Linux/Unix:
#include <cstdlib>
int main() {
std::system("clear");
return 0;
}
回答8:
This is REALLY choppy but try:
void cls() {
for (int i = 0; i < 250; ++i) {
std::cout << endl;
}
}
回答9:
Use system("cls")
to clear the screen:
#include <stdlib.h>
int main(void)
{
system("cls");
return 0;
}
回答10:
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.
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}
回答11:
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
}
回答12:
Here is a simple way to do it:
#include <iostream>
using namespace std;
int main()
{
cout.flush(); // Flush the output stream
system("clear"); // Clear the console with the "system" function
}
回答13:
In Windows we have multiple options :
clrscr() (Header File : conio.h)
system("cls") (Header File : stdlib.h)
In Linux, use system("clear") (Header File : stdlib.h)
回答14:
Use System::Console::Clear();
This will clear (empty) the buffer
回答15:
#include <cstdlib>
void cls(){
#if defined(_WIN32) //if windows
system("cls");
#else
system("clear"); //if other
#endif //finish
}
The just call cls() anywhere
回答16:
You can use the operating system's clear console method via system("");
for windows it would be system("cls"); for example
and instead of releasing three different codes for different operating systems. just make a method to get what os is running.
you can do this by detecting if unique system variables exist with #ifdef
e.g.
enum OPERATINGSYSTEM = {windows = 0, mac = 1, linux = 2 /*etc you get the point*/};
void getOs(){
#ifdef _WIN32
return OPERATINGSYSTEM.windows
#elif __APPLE__ //etc you get the point
#endif
}
int main(){
int id = getOs();
if(id == OPERATINGSYSTEM.windows){
system("CLS");
}else if (id == OPERATINGSYSTEM.mac){
system("CLEAR");
} //etc you get the point
}
回答17:
edit: completely redone question
Simply test what system they are on and send a system command depending on the system. though this will be set at compile time
#ifdef __WIN32
system("cls");
#else
system("clear"); // most other systems use this
#endif
This is a completely new method!
回答18:
use: clrscr();
#include <iostream>
using namespace std;
int main()
{
clrscr();
cout << "Hello World!" << endl;
return 0;
}
回答19:
The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.
int main(int argc, char *argv)
{
for(int i = 0; i <1024*1024; i++)
std::cout << ' ' << std::endl;
return 0;
}
The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.
来源:https://stackoverflow.com/questions/6486289/how-can-i-clear-console