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

I am trying to print characters in the console with the specified coordinates. So far I have used the very ugly one printf("\033[%d;%dH%s\n", 2, 2, "str");But I just needed to ask if C ++ had any other way to do this. The problem is not that it is ugly, the problem arises when I try to make myself a more beautiful function:

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

This does not work even if I resort to (char*). Another problem is that I have to print \nto refresh the page ... I just don't like to use it printfat all.

Similarly, use coutinstead printf, I believe that there should be a fresh way to do it (ideally, it allows me to write a line where I want to on the screen, and, ideally, does not require these strange characters \033[%d;%dH)

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

+5
source share
7 answers

What you are doing is using some very terminal-specific magic characters in another pure C ++ application. Although this works, it will probably be much easier for you to use a library that abstracts you from having to deal with detailed information about specific terminal terms and provides functions that do what you need.

, curses ncurses .

+5

Curses - , .

+11

, gotoxy(x,y) Turbo ++ (conio.h) - , , , x y.

EDIT: Windows, gotoxy clone: ​​

#include <windows.h>

void gotoxy(int x, int y)
{
  COORD coord;
  coord.X = x;
  coord.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
+8

:

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

, (const). , () char* std::string - - c_str():

void printToCoordinates(int x, int y, const std::string& text)
{
    printf("\033[%d;%dH%s\n", x, x, text.c_str());
}

: ++ , , . , .

+3

:

void printToCoordinates(int x, int y, const char *format, ...)
{
    va_list args;
    va_start(args, format);
    printf("\033[%d;%dH", x, y);
    vprintf(format, args);
    va_end(args);
    fflush(stdout);
}

:

  • stdout
  • x y ( x x )

, varargs C ++, :

printToCoordinates(10, 10, "%s", text.c_str());

curses ( Unix- ) Win32 ( Windows), .

+2
void screenpos(int x,int y,char textyowanawrite[20])
{
//printf for right shift
// \n for downward shift
//loops through the rows and shifts down 
for(int row=0;row<=y;row++)
{
printf("\n");
for (int i = 0; i < x; i++)
{
printf("%s "," " );
}
}
printf("%s ",textyowanawrite );
} 

// ,  - 4,4 2,2,

0

. , , ncurses, , .

++ . outtextxy(x, y, text) ; x y - .

:

int main(void) {

    int gdriver = DETECT, gmode;

    int x = 200, y = 200;

  

    initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

  

    outtextxy(x, y, "Hello World");

    closegraph();

 }

This small program prints Hello World at (200,200).

For help on which graphics package you can make, visit this link.

-1
source

All Articles