gotoxy() function using printf() 's position

18,847

Solution 1

The order of x and y matters because the names of the variables have no meaning to the operation of the gotoxy() function.

That function is outputing a terminal command sequence that moves to the specified coordinates. When the terminal sees that command sequence and processes it, y is expected first.

By the way, be careful with this solution as this is highly dependent on the type of terminal within which the program is run. In order to get wide terminal support with random movement and "drawing" on a terminal screen, ncurses or curses are your best bet. They are challenging to learn at first though.

Solution 2

OP: "why the need to change the x y order".
The cursor position command's format is

Force Cursor Position   <ESC>[{ROW};{COLUMN}f

The need arises because to match that format and have your y variable as the ROW, y comes first. (You could rotate your screen 90 degrees instead).

OP: why cursor does't go to second row when i = 1?
The home position, at the upper left of the screen is the Origin being line 1, column 1

Note: You can put the escape character in the format,

printf("\x1B[%d;%df", y, x);
fflush(stdout);  // @jxh

Solution 3

The column and row positions do not start at 0 when using the terminal escape sequences. They start at 1.

You need to flush stdout to see the cursor move.

void gotoxy(int x,int y)
{
    printf("%c[%d;%df",0x1B,y,x);
    fflush(stdout);
}
Share:
18,847
good5dog5
Author by

good5dog5

Updated on June 15, 2022

Comments

  • good5dog5
    good5dog5 almost 2 years

    Hello there
    i am working a project which need the gotoxy() function
    i have read gotoxy() implementation for Linux using printf

    i wonder why the

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

    need to change the x y order in printf, is that just to fit the coordinate system?
    in my way, i change it to printf("%c[%d;%df",0x1B,x,y) to meet my needs

    stil, during my using this gotoxy() in for loop like this:

    for( int i = 0; i < 12; i++ ) {
            for( int j = 0; j < 12; j++ ) {
                gotoxy( i , j );
                usleep(500000);
            }
        }
    

    when i = 0 and i = 0, the cursor are on the first row
    i wonder why cursor does't go to second row when i = 1?

  • ryyker
    ryyker over 10 years
    showing how <ESC>[{ROW};{COLUMN}f relates to the function brought the whole thing home for me.