How to delete the terminal from what was written when running a C program?

Asked

Viewed 498 times

0

People I am with a tremendous doubt. When I run a program in C it shows the information that are in the terminal. But then I want to delete what was written to show a new information. I have done some research and I have not found anything to solve this problem. I’ve tried some of the things I found, but it didn’t work. I’m new to programming and I’m doing a job for college <- not worth noting, but I wanted to leave the program with a good visibility. NOTE: I HAVEN’T FINISHED ALL ACTIVITY YET. Thank you in advance. Thank you!

#include <stdio.h>
#include <locale.h>
int somar (){

    return 2+5;
}

int main() { //O algoritmo é pra executar uma serie de atividades usando função
  setlocale(LC_ALL, "portuguese");

  int n, funcao;
  char caso;

do{

  printf ("\n ******************************************");
  printf ("\n **    Escolha abaixo uma das opções   **\n");
  printf (" ******************************************\n\n");

  printf (" ----> Atividade 1 = digite (1)\n");
  printf (" ----> Atividade 2 = digite (2)\n");
  printf (" ----> Atividade 3 = digite (3)\n");
  printf (" ----> Atividade 4 = digite (4)\n");
  printf (" ----> Atividade 5 = digite (5)\n");
  printf (" ----> Atividade 6 = digite (6)\n");
  printf (" ----> Atividade 7 = digite (7)\n");
  printf (" ----> Atividade 8 = digite (8)\n\n");

  scanf ("%s", &caso);

  //após a escolha da opção quero que saia da tela o que está escrito acima do comentario

switch (caso) {
    case '1':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '2':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '3':
        funcao=somar();
        printf ("%d", funcao);
        break;

     case '4':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '5':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '6':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '7':
        funcao=somar();
        printf ("%d", funcao);
        break;

    case '8':
        funcao=somar();
        printf ("%d", funcao);
        break;


    default: printf ("\n\t**********OPÇÃO ERRADA**********");
  }

  printf ("\n\n\nDeseja fazer outra oeração?\n\n--->Digite 0 para sim.\n--->Digite qualquer numero para sair.\n");
  scanf ("%d", &n);
} while (n==0); //ao final do do-while também quero que apague tudo o que foi escrito
// pra quando iniciar novamente o programa inicie limpinho o terminal.

  return 0;
}


2 answers

1


Clearing the screen in C is a very controversial subject. You have several ways to do this from a user point of view, but I’ve never seen a consensus among programmers due to lack of portability. As it is a college activity, I would recommend not trying very elaborate methods, as it would be difficult to make an explanation of these.

For Windows you can include the stdlib. h library and use the system("cls command"):

#include <stdlib.h>

system("cls");

The equivalent in Linux would be:

#include <stdlib.h>

system("clear");

Another way would be to use libraries like "conio" for Windows and "ncurses" for Linux.

#include <conio.h>

clrscr();

I’m not going to put the way here using ncurses because I’ve had some problems, and I don’t want to induce you to do things that don’t work. In addition to these methods cited, there are numerous others, but more elaborate. I do not recommend using them in your work. I will give some examples.

You can use the windows library. h to take the dimensions of the terminal, and print as many "spaces" as necessary, or even quanas line breaks.

#include <windows.h>

int get_cmd_nrows(){
   CONSOLE_SCREEN_BUFFER_INFO csbi;
   GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
   return(csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
int get_cmd_ncols(){
   CONSOLE_SCREEN_BUFFER_INFO csbi;
   GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
   return(csbi.srWindow.Right - csbi.srWindow.Left + 1);
}
void clear1() { //método com espaços
   int i, r, c;
   r = get_cmd_nrows();
   c = get_cmd_ncols();
   for(i = 0;i<r*c;i++) {
       printf(" ");
   }
}
void clear2() {
   int i, r; //Método usando quebras de linha
   r = get_cmd_nrows();
   for(i = 0;i<r ;i++) {
       printf("\n");
   }
}

Look, it’s starting to get a lot more abstract. Here’s another example that works on Linux-based systems (By using a terminal that matches such characters).

First set the escape character (" 033[") and then the CLEAR character, which will be used in our clear() function. H to return the cursor to the source, and J to clear the screen. After that, just print this code on the screen. Or do so:

#define ESC             "\033["
#define CLEAR           ESC "H" ESC "J"

void eval(const char * cd) {
   printf("%s", cd);
}

void clear() {
   eval(CLEAR);
}

From there, just call the function clear(). Anyway, there are other ways, but I believe I have given to understand the proposal.

  • Thank you very much for your reply, I have already given it to the teacher to correct. But as soon as I do more things in C programming. I will use these different techniques you gave me. I will even test now. Vlww

0

Use system() to do something is not actually doing something in a program. And it is something condemned or prohibited in many places for security reasons. It’s like someone asking you the way to a street and you make an intellectual face and tell them how to search in Google Maps. :D

In windows the official to clear the "screen", which by default has 9001 lines, is something like this in C or C++

int     cls()
{   // limpa a tela no windows, do jeito oficial
    CONSOLE_SCREEN_BUFFER_INFO      info;
    HANDLE      H = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD       origem = { 0,0 };
    int         total;
    if (H == INVALID_HANDLE_VALUE) return -1;
    GetConsoleScreenBufferInfo(H, &info);
    int r = FillConsoleOutputCharacter(H, (TCHAR)' ',
        info.dwSize.X * info.dwSize.Y,
        origem, &total);
    int s = FillConsoleOutputAttribute(
        H, info.wAttributes,
        info.dwSize.X * info.dwSize.Y,
        origem, &total);
    SetConsoleCursorPosition(H, origem);
    return 0;
};  // end cls()

And the logic is described in The Console Bible

You get an Handle to access the console window, calls GetConsoleScreenBufferInfo() to see the current window size and the above routines to fill the whole area with spaces and with the attribute in use. And must "clean" even the attribute or previous changes of color or bold for example may appear again.

A bit of history

In Unix/Linux/Mac this console concept does not exist. Programs write to the "terminal" using an emulator. Terminal. The programming model of Unix is from the 70’s. Windows from the 80’s. : ) In Unix the terminals were like this, terminals. With plug, font, keyboard and a serial port. And it was hell because each brand was one way.

Over time the thing evolved into a model based on a structure called terminfo that still exists today. And is a command reference for the terminal.

In general the commands used are a legacy of the commands of the Digital terminals, in particular the VT-52 and VT-100 and VT-240. Commands that start with ESC[ and are hundreds of them. Linux has no screen memory, the letters were sent by the system one by one through the serial port. A known way to clear the screen was to TURN off the terminal and turn it back on. Old times. The other more modern was to access terminfo and see how many lines had the terminal, and then write so many return/line feed how many lines has the terminal, "wiping the screen" because the terminal has no memory or scroll.

One of the most powerful commands in the terminfo is the reset and you can run on your terminal a reset ``tput e vai ser o equivalente a ligar e desligar o terminal, limpando a tela. tput reset is what makes the command clear, as far as I know.

Not having the image of the screen is a hell and so curses was so useful. nowadays emulators tty has scroll and memory, but the programming model has not changed at all. ncurses is still the shortest way if you need to be able to use text windows and more sophisticated things without graphical interface: ncurses has overlapping windows, screen image, treats the keyboard well, optimizes the use of the display and its programming model is very simple.

The "new" Windows console

However, as of 2018, Microsoft has spent a fortune implementing the Linux programming model for the Windows console and now everything is even more confusing. More about this here, straight from Microsoft

What happens is that with the migration of computers in their millions to the cloud, in the opposite of the migration of the 1980s when applications started to move from mainframes to minicomputers and then to personal computers, now everything is coming back to that cloud. And computers have no graphical interface and administration is in many cases via text. And then a single programming model makes perfect sense.

I was going to keep writing but I don’t think anyone’s going to read and I’m moving away from the topic...

This new model is described here https://docs.microsoft.com/en-us/windows/console/console-functions

Browser other questions tagged

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