How to clear the screen in C++?

Asked

Viewed 15,220 times

2

How to clear the screen in C++ ? I already put the library: ** #include< stdlib. h>** and the code: system("cls"), but gives the error: "sh: 1: cls: not found". How do I fix this?

2 answers

5

Deleting the screen is an operation dependent on the environment in which the program operates. For example, a graphical program does not even have this operation, because it is not running in a terminal.

That being said, it looks like you are running the program in a UNIX/Linux environment, so I suggest replacing "cls" with "clear", because "cls" is the MS-DOS/Windows command line instruction to clear the screen.

2

As already said, it depends on the environment, however as suggested I already fear the command:

clear

Which is usually used on Unix-like systems (linux for example) and the command:

cls

Used on Windows systems.

If the error occurs it may be because it is running cls on a Linux system (or similar).

To create a 'certain compatibility' between different systems can be a little complex, there are those who suggest using the compiler definitions, for example (is a very simple example):

#if defined(_WIN32) || defined(_WIN64)
    system("cls");
#else defined(__linux__) || defined(__unix__)
    system("clear");
#endif

But this of course may vary a lot for each compiler, or maybe the available compilers or libs use other definitions to identify the system that was compiled, so a suggestion that I think would be more guaranteed would be to use in the command itself the || and with this pass both commands (cls and clear), for example:

system("clear||cls");

The above command will execute like this, first it tries to execute the clear, if it is a command available in the user’s system then it will run, otherwise it will try to run cls.

This can make your program a little more "portable" between different systems without worrying so much about different types of compilers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.