System cls no linux

How do I clear the console in BOTH Windows and Linux using C++

I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don’t want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).

The console does not even exist in standard C++11, so pedantically your question does not even make any sense. And what about your program foo being redirected (e.g. foo > output.txt ) or pipelined (e.g. foo | grep xxx ) ? BTW, some computers don’t have any consoles (e.g. most web servers or VPS)

13 Answers 13

#include void clear_screen() < #ifdef WINDOWS std::system("cls"); #else // Assume POSIX std::system ("clear"); #endif >

This is the most concise, general-purpose answer that will work in 99% of all cases. Should be the accepted answer.

Longer answer: Use a curses library (ncurses on Unix, pdcurses on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows).

Most difficult answer: Use #ifdef _WIN32 and stuff like that to make your code act differently on different operating systems.

On linux it’s possible to clear the console. The finest way is to write the following escape sequence to stdout:

which is what /usr/bin/clear does, without the overhead of creating another process.

To be clear: [H moves the cursor to the top-left of the screen [2J erases the screen Anyone wanting more details should Google «ANSI escape sequences».

error: no matching function for call to ‘write’ write(1,»\E[H\E[2J»,7); // we use ANSI escape sequences here. ^~~~~ And I did the includes and checked the namespace.

A simple trick: Why not checking the OS type by using macros in combination with using the system() command for clearing the console? This way, you are going to execute a system command with the appropriate console command as parameter.

#ifdef _WIN32 #define CLEAR "cls" #else //In any other OS #define CLEAR "clear" #endif //And in the point you want to clear the screen: //. system(CLEAR); //. 

Short answer

Long answer, please read:

The question as posted is unanswerable, because it imposes impossible restrictions. «Clearing the screen» is a very different action across different operating systems, and how one does it is operating system specific. See this Frequently Given Answer for a full explanation of how to do it on several popular platforms with «consoles» and platforms with «terminals». You’ll also find in the same place some explanation of the common mistakes to avoid, several of which are — alas! — given above as answers.

Читайте также:  Remote linux debugger ida

This is how you do it on any other platform but it doesn’t work in Windows:

Perhaps you’ll need to make a conditional compilation:

void clrscr() < #ifdef _WIN32 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord = ; DWORD count; CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hStdOut, &csbi); FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count); SetConsoleCursorPosition(hStdOut, coord); #else cout

I know this isn't answering my own question but! This works for Windows ( #include ):

void clrscr() < HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord = ; DWORD count; CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hStdOut, &csbi); FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count); SetConsoleCursorPosition(hStdOut, coord); > 

Well there is a very close alternative to clearing the screen. You could try using a for loop that repeats new lines a lot. For example:

After you do this loop the terminal wan't allow you to scroll back to where you were at the top, an unprofessional approach with common sense pretty much. It does not directly answer what you are asking but it can work.

This code clears the console in BOTH Windows and Unix (Although it's actually compiled differently):

// File: clear_screen.h #ifndef _CLEAR_SCREEN_H #define _CLEAR_SCREEN_H void clearScreen(void); /* Clears the screen */ #endif /* _CLEAR_SCREEN_H */ 
// File: clear_screen.c #ifdef _WIN32 #include void clearScreen(void) < HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); COORD topLeft = ; DWORD dwCount, dwSize; CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hOutput, &csbi); dwSize = csbi.dwSize.X * csbi.dwSize.Y; FillConsoleOutputCharacter(hOutput, 0x20, dwSize, topLeft, &dwCount); FillConsoleOutputAttribute(hOutput, 0x07, dwSize, topLeft, &dwCount); SetConsoleCursorPosition(hOutput, topLeft); > #endif /* _WIN32 */ #ifdef __unix__ #include void clearScreen(void) < printf("\x1B[2J"); >#endif /* __unix__ */ 

As others have already said, there's no way to have one identical piece of code that clears the console on both Windows and Linux.

I'll also strongly recommend against using std::system :

  • it makes your program vulnerable to attacks; what if someone replaced clear / cls with their own malicious program
  • as a consequence of the above, antivirus programs hate std::system . If your code uses it, the resulting binary may test positive for virus even if it's meant to be harmless. (Note that it is not actually harmless.)
#ifdef _WIN32 #include #endif void clrscr() < #ifdef _WIN32 COORD tl = < 0,0 >; CONSOLE_SCREEN_BUFFER_INFO s; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(console, &s); DWORD written, cells = s.dwSize.X * s.dwSize.Y; FillConsoleOutputCharacter(console, ' ', cells, tl, &written); FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written); SetConsoleCursorPosition(console, tl); #else std::cout

You may follow the pattern shown above, and change the two code segments anyway you like.

Источник

How to clear screen in c++ ?

Mainly when we are working with console application in C/C++ we come across some scenario where we need clear screen using C++ or C programing language.

There are many different ways available for c++ clear screen.

C++ clear screen in turbo C++ compiler

In Turbo c++ compiler you can use clrscr (); for clear screen.

For c++ clear screen you will require to add conio.h header file.

C++ clear screen in Visual C++ or other IDE

For clear screen in C++ you can use system(“CLS”);

You will require to add standard library header file

You can also use system command with clear also example: system(“clear”); It is normally used in POSIX.

Flushing output stream by flush

You can add flush at the end for cout.

Clear screen in C++ in both Windows and Linux:

This is special string which is similar to clrscr();

Читайте также:  Mount nfs linux команда

c++ clear screen without SYSTEM(“cls”)

This is not efficient way but by adding many \n it will automatically clear current screen.

Also in C++ if want to flush we can use cout.flush() function also.

Conclusion:

We have described many different solutions for c++ clear screen. Again it might depend on which IDE and compiler of C++ you are using. It also depend on Operating system you are using for C++ development. some solution might not work for you. You can try all given solution and one of solution will surely work for clearing screen in C++. In case if you are facing any issue you can contact us or comment you problem we will like to help you for same.

Reader Interactions

Leave a Reply Cancel reply

Primary Sidebar

Search here

Social Media

SEE MORE

Fibonacci sequence c++

Fibonacci Sequence c++ is a number sequence which created by sum of previous two numbers. First two number of series are 0 and 1. And then using these two number Fibonacci series is create like 0, 1, (0+1)=1, (1+1)=2, (2+1)=3, (2+3)=5 …etc Displaying Fibonacci Series in C++ ( without recursion) Output: From given output we […]

map c++

C++ Map [Learn by Example]

C++ map is part of Standard Template Library (STL). It is type of Associative container. Map in c++ is used to store unique key and it’s value in data structure. But if you want to store non-unique key value then you can use Multi Map in c++. Let us first understand in detail what is […]

how to copy paste in turbo c++ ?

There are many different C++ IDE are available but still many students are using Turbo c++ for learning c/c++ programming languages. During using Turbo c++ if you are beginner you will be confuse for how to copy and paste in turbo c++ or if you have already copy some content and you want to paste […]

C++

return 0 c++

There are two different scenario return statement is used inside c++ programming. We can use return 0 c++ inside main() function or other user defined functions also. But both have different meanings. return 0 c++ used inside Main function return 0 c++ used inside other user defined function What is meaning of return 0 and […]

C++

c++ expected a declaration [ SOLVED]

When any function or statement is not in scope or we have used wrong syntax then possibly you will get error for c++ expected a declaration in your code. Main reasons for errors are: Incorrect use/declaration inside namespace Statements are added out of scope Required statement need to add inside main/function Solution-1 | Expected a […]

C++

c++ cannot open source file “errno.h” [SOLVED]

Normally you will face c++ cannot open source file “errno.h” in MS Visual Studio c++ projects. These are some solutions to remove opening errors for “errno.h” file. I got the errors to go away by installing the Windows Universal CRT SDK component, which adds support for legacy Windows SDKs. You can install this using the […]

Источник

How can I clear console

I asked how to do this in C, using a console window handle. This is the answer I received. Hopefully, it helps with your case.

19 Answers 19

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.

Читайте также:  Astra linux special edition антивирус

See this entry in the comp.lang.c++ FAQ:

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:

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:

the origin don't matter -- code that won't even compile (with g++) is ungood. But since you fixed it I removed downvote. 🙂

@YoushaAleayoub edited the answer to remove the MS link suggesting to use system , and added a link to your article explaining why.

For those looking for the removed link: support.microsoft.com/kb/99261 although, the code is a simple call to system(cls); with the cstdlib include. Tread lightly.

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:

Using system for this is just ugly.

@MerlynMorgan-Graham: It spawns a shell process to clear a friggin' console. In what way is that a clean solution? 😛 It's like using echo via system() instead of writing to stdout.

One liner FTW! 😉 Yes, I'm being facetious. The fact that it spawns a shell process is good info for your answer, tho. +1 for the *nix version.

The easiest way for me without having to reinvent the wheel.

  • On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
  • On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences

For Linux/Unix and maybe some others but not for Windows before 10 TH2:

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 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 #include void ClearScreen() < if (!cur_term) < int result; setupterm( NULL, STDOUT_FILENO, &result ); if (result putp( tigetstr( "clear" ) ); > 

Источник

Оцените статью
Adblock
detector