Tuesday, April 4, 2023

gotoxy(int x, int y); and clrscr() in linux terminal (command prompt)

 

#include <sys/ioctl.h>
#include <unistd.h>
 

void gotoxy(int x,int y)
{
    printf("%c[%d;%df",0x1B,y,x);

-----------------------------------------------------------------------------

use above code to place cursor  any where in terminal e.g gotoxy(4, 10);

places (x, y) co-ordinate as (4, 10). 4th column and 10th row.

 example :-

#include <iostream>

#include <sys/ioctl.h>
#include <unistd.h>
  

using std::cout;

using std::cin;

void gotoxy(int x,int y)
{
    printf("%c[%d;%df",0x1B,y,x);

}

int main()

{

    gotoxy(5, 10);

    cout << "Here is Cursur : " ;

    cin >> x;

    return 0;

}

----------------------------------------------------------------------

example :-

#include <iostream>

#include <sys/ioctl.h>
#include <unistd.h>

#include <termio.h>
#include <cstdio>
#include <iomanip>



using std::cout;

using std::cin;

void gotoxy(int x,int y)
{
    printf("%c[%d;%df",0x1B,y,x);

}

static termios oldterm, newterm;
 void clrscr()
{
        gotoxy(0,0);

        struct winsize w;
        ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

        for (int x = 0; x < w.ws_row; x++)
        {
            for(int y = 0; y < w.ws_col; y++)
            {
                cout << " ";
            }
        }
        gotoxy(0, 0);
}

void initTermios(bool echo)
{
    tcgetattr(0, &oldterm);
    newterm = oldterm;
    newterm.c_lflag &= ~ICANON;
    newterm.c_lflag &= echo ? ECHO : ~ECHO;
    tcsetattr(0, TCSANOW, &newterm);
}

void resetTermios()
{
    tcsetattr(0, TCSANOW, &oldterm);
}

char getch_(bool echo)
{
     char ch;
     initTermios(echo);
     ch = getchar();
     resetTermios();
     return ch;
}


char getch()
{
    return getch_(false);
}

char getche()
{
    return getch_(true);
}

int main()

{

    char x;
     clrscr();
    gotoxy(5, 10);

    cout << "Here is Cursur : " ;

    cin >> x;

    gotoxy(5, 11);
    cout << "you entered : " << x;


    getch();
    getch();
    clrscr();

    return 0;

}



No comments:

Post a Comment