Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print a string to the console at specific coordinates in C++?

I'm trying to print characters in the console at specified coordinates. Up to now I have been using the very ugly printf("\033[%d;%dH%s\n", 2, 2, "str"); But I just had to ask whether C++ had any other way of doing this. The problem is not even that it's ugly, the problem comes up when I try to make myself a prettier function like so:

void printToCoordinates(int x, int y, string text)
{
    printf("\033[%d;%dH%s\n", x, x, text);
}

It doesn't work, even if I typecast to (char*). Another problem is that I have to print out the \n for the page to be refreshed... I just don't enjoy using printf in general.

Similarily to using cout instead of printf, I believe there should be a more recent way of doing this (ideally a way that allows me to easily write strings where I want on the screen, and ideally a way that doesn't required these weird symbols: \033[%d;%dH)

So, do any of you have what I'm looking for?

like image 744
Shawn Avatar asked Nov 03 '09 23:11

Shawn


2 Answers

Curses is what you are looking for.

like image 85
Dima Avatar answered Oct 05 '22 22:10

Dima


What you are doing is using some very terminal specific magic characters in an otherwise pure C++ application. While this works, you will probably have a far easier time using a library which abstracts you from having to deal with terminal specific implementation details and provides functions that do what you need.

Investigate whether curses or ncurses libraries are available for your system.

like image 41
CB Bailey Avatar answered Oct 06 '22 00:10

CB Bailey