How to Print a String to the Console at Specific Coordinates in C++

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

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.

How do you put a string starting from a specific position?

You can write a function to do this. For example:

static void Print(int left, int top, params string[] lines)
{
foreach (string line in lines)
{
Console.SetCursorPosition(left, top);
Console.WriteLine(line);
top++;
}
}

And call it like this:

Print(50, 1, "Hello", "World");

Or equivalently like this:

string[] lines = { "Hello", "World" };
Print(50, 1, lines);

If the text consists of words separated by spaces, and you want to put a single word on each line, then you can split the text at spaces, inside the function. That way you would be able to pass a single line of text.

static void Print(int left, int top, params string[] lines)
{
foreach (string line in lines)
{
string[] words = line.Trim().Split(new char[] { ' ' });
foreach (string word in words)
{
Console.SetCursorPosition(left, top);
Console.WriteLine(word);
top++;
}
}
}

And call it like this:

Print(50, 1, "Hello World");

how to output text to console to specific coordinates without moving the cursor coordinates in c++

Assuming you are using ncurses or something like that? So your console terminal is a shared resource, you have to protect it with a mutex and take care for the cursor positioning in each thread. You could also declare one thread the boss which has its cursor-position restored by the other thread. That other thread then would, after aquiring the mutex, do something like getcurx, getcury, do its own positioning and outout, and then restore the cursor pos retrieved with getcurx/y.

note that in each case, all threads need to aquire the mutex before accessing the terminal.

You can also check wether you can come along with the builtin thread support in ncurses, look out for use_screen, use_window



Related Topics



Leave a reply



Submit