code

콘솔을 어떻게 지울 수 있습니까?

codestyles 2020. 10. 10. 10:05
반응형

콘솔을 어떻게 지울 수 있습니까?


제목에서와 같이. C ++에서 콘솔을 어떻게 지울 수 있습니까?


순수 C ++ 용

당신은 할 수 없습니다. C ++에는 콘솔이라는 개념조차 없습니다.

프로그램은 프린터로 인쇄하거나 파일로 직접 출력하거나 다른 프로그램의 입력으로 리디렉션 될 수 있습니다. C ++에서 콘솔을 지울 수 있더라도 이러한 경우는 훨씬 더 복잡해집니다.

comp.lang.c ++ FAQ에서 다음 항목을 참조하십시오.

OS 별

프로그램에서 콘솔을 지우는 것이 여전히 타당하고 운영 체제 별 솔루션에 관심이 있다면 해당 솔루션이 존재합니다.

Windows의 경우 (태그에서와 같이) 다음 링크를 확인하십시오.

편집 : system("cls");Microsoft가 그렇게 말했기 때문에 이전에을 사용하여 언급 한이 답변 입니다. 그러나 이것은 안전한 일이 아니라는 의견에서 지적되었습니다 . 이 문제로 인해 Microsoft 문서에 대한 링크를 제거했습니다.

라이브러리 (다소 이식 가능)

ncurses는 콘솔 조작을 지원하는 라이브러리입니다.


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);
}

가능한 모든 오류를 기꺼이 무시하지만 콘솔 지우기입니다. 아니 같은 system("cls")더 나은 핸들 오류가 발생합니다.

* nixes의 경우 일반적으로 ANSI 이스케이프 코드를 사용할 수 있으므로 다음과 같습니다.

void clear() {
    // CSI[2J clears screen, CSI[H moves the cursor to top-left corner
    std::cout << "\x1B[2J\x1B[H";
}

system이것을 사용 하는 것은 추악합니다.


Linux / Unix 및 기타 일부의 경우 (10 TH2 이전의 Windows에는 해당되지 않음) :

printf("\033c");

터미널을 재설정합니다.


창 콘솔에 여러 줄을 출력하는 것은 쓸모가 없습니다. 단지 빈 줄을 추가합니다. 슬프게도 방법은 창에 따라 다르며 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 );
  }

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" ) );
  }

// #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;
}

화면을 지우려면 먼저 모듈을 포함해야합니다.

#include <stdlib.h>

이것은 Windows 명령을 가져옵니다. 그런 다음 '시스템'기능을 사용하여 배치 명령 (콘솔 편집)을 실행할 수 있습니다. C ++의 Windows에서 화면을 지우는 명령은 다음과 같습니다.

system("CLS");

그러면 콘솔이 지워집니다. 전체 코드는 다음과 같습니다.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
system("CLS");
}

그리고 그게 전부입니다! 행운을 빕니다 :)


Windows에서 :

#include <cstdlib>

int main() { 
    std::system("cls");
    return 0;
}

Linux / Unix :

#include <cstdlib>

int main() { 
    std::system("clear");
    return 0;
}

이것은 정말 고르지 않지만 시도해보십시오.

void cls() {
    for (int i = 0; i < 250; ++i) {
        std::cout << endl;
    }
}

Use system("cls") to clear the screen:

#include <stdlib.h>

int main(void)
{
    system("cls");
    return 0;
}

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);
}

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
}

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
}

In Windows we have multiple options :

  1. clrscr() (Header File : conio.h)

  2. system("cls") (Header File : stdlib.h)

In Linux, use system("clear") (Header File : stdlib.h)


Use System::Console::Clear();

This will clear (empty) the buffer


#include <cstdlib>

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

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

}

The just call cls() anywhere


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

}

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!


use: clrscr();

#include <iostream>
using namespace std;
int main()
      {           
         clrscr();
         cout << "Hello World!" << endl;
         return 0;
      }

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.

참고URL : https://stackoverflow.com/questions/6486289/how-can-i-clear-console

반응형