Question

I found this code for a replacement gotoxy() function using C standard library only. apparently it compiles using GCC and works like the gotoxy() found in conio.h.

However I only have Borland C++ v5.5 compiler, this compiles fine but does not reposition the curser like gotoxy() in conio.h does. Can anybody verify the fact that this works when using GCC or tell me why it doesn't work using Borland?

#include<stdio.h>
#include<stdlib.h>

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

int main()
{
    gotoxy(10, 10);
    printf("hello world");
}
Was it helpful?

Solution

The escape codes being used in your function depend on support being present in your terminal emulator. It may or may not work, depending on the environment you're using. For example, your program works as expected in Mac OS X's Terminal application, running bash in xterm compatibility mode.

You can read about ANSI escape codes for more information about this specific case, which is the "HVP – Horizontal and Vertical Position" command.

OTHER TIPS

That code prints an ANSI escape sequence: <esc>[y;xf, so will only work on an ANSI terminal, or a terminal emulator that supports ANSI codes.

The issue isn't GCC vs BC++, but running in a unix-style terminal emulator that supports ANSI codes vs the Windows CMD window.

EDIT: try changing the body of gotoxy() to the following. The escape code in your sample moves the cursor to a previous line. The code ending in H should position the cursor to the requested (Y,X) coordinate.

printf("%c[%d;%dH", 0x1B, y, x);

EDIT2: since the asker is using the Windows CMD console, the correct solution is to use SetConsoleCursorPosition(). ANSI escapes aren't supported, or are incompletely supported in Win2k and later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top