Pergunta

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?

Foi útil?

Solução 2

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.

Outras dicas

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

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

GotoXY is a function or procedure that positions the cursor at (X,Y), X in horizontal, Y in vertical direction relative to the origin of the current window. The origin is located at (1,1), the upper-left corner of the window.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top