1ann0x
1ann0x

Reputation: 24

how to clear screen after taking input from user in C++?

I have tried using:

  1. cout<<"033[2j\033[01;1H"; I don't understand what it did to the terminal. Output: On the terminal

  2. cout<<string(22, '\n'); This solution took the cursor 22 lines below, which I didn't want.

  3. system('cls'); I included stdlib.h for it but I still got the same error and I'm unable to resolve it. Output: On the terminal

These were the solutions I could find but they don't help.

This is the code I'm trying it on:

#include <iostream>
using namespace std;

void rev_array(int arr[], int start, int end)
{
    while(start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

void print_array(int arr[], int size)
{
    for(int i=0; i < size; i++)
    cout<<arr[i]<<" ";

    cout<<endl;
}

int main()
{
    int n;
    cout<<"Enter the size of array: ";
    cin>>n;
    int arr[n];
    for(int i=0; i<n; i++)
    cin>>arr[i];

    cout<<"033[2j\033[01;1H";
    
    print_array(arr, n);
    rev_array(arr, 0, n-1);

    cout<<"Reversed array is "<<endl;
    print_array(arr, n);
    return 0;
}

Upvotes: 0

Views: 2024

Answers (2)

Abdul Rawoof Shaik
Abdul Rawoof Shaik

Reputation: 73

system() function invokes the command given as parameter.

To clear the screen on windows based system, you can call (please use the double quotes around cls command):

system("cls");

On Unix based system use "clear" command:

system("clear");

Upvotes: 2

selbie
selbie

Reputation: 104589

This line:

cout<<"033[2j\033[01;1H";

You are missing a leading \ to indicate an octal escape at the start of the string. And when I corrected that, it would only position the cursor to the top of the Linux terminal, not clear it.

I'm not an expert in ANSI escape sequences, but a quick internet search reveals this is the way to clear the screen with ANSI escape sequences.

cout << "\033[2J\033[;H";

That worked for me on Linux. And it would probably work on MacOS and other Unix variants as well. But it won't work on Windows out of the box. To enable ANSI mode on Windows 10, paste the code below appropriately into your program and invoke EnableAnsi from main.

#include <windows.h>
void EnableAnsi()
{
    DWORD dwMode = 0;
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleMode(hOut, &dwMode);
    dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    SetConsoleMode(hOut, dwMode);
}

Upvotes: 3

Related Questions