How can I clear console

2019-01-02 23:42发布

As in the title. How can I clear console in C++?

18条回答
姐就是有狂的资本
2楼-- · 2019-01-03 00:03

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

}
查看更多
beautiful°
3楼-- · 2019-01-03 00:06

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 :)

查看更多
贪生不怕死
4楼-- · 2019-01-03 00:07

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
}
查看更多
唯我独甜
5楼-- · 2019-01-03 00:09
#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish

}

The just call cls() anywhere

查看更多
劫难
6楼-- · 2019-01-03 00:09

use: clrscr();

#include <iostream>
using namespace std;
int main()
      {           
         clrscr();
         cout << "Hello World!" << endl;
         return 0;
      }
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-03 00: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);
}
查看更多
登录 后发表回答