Console cursor coordinates in C

Asked

Viewed 516 times

3

Taking the following code as an example:

#include <stdio.h>

int main(void)
{
    printf("Hello world");
    return 0;
}

Where "Hello World" will be written in row 1 and column 1 of the console. How do I change this, for example, write it in row 3, column 5?

1 answer

3


There is no standard way to do this, it depends on the console library you are using. On Linux it usually works:

void gotoxy(int x, int y) {
    printf("\033[%d;%dH", x, y);
}

Under Windows you can use SetConsoleCursorPosition().

void gotoxy(int x, int y) { 
    COORD pos = {x, y};
    HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(output, pos);
}

I put in the Github for future reference.

  • Just to add, it is necessary to give include in windows. h to be able to use this function.

  • It worked, vlw :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.