Reputation:
I have used <windows.h>
and <conio.h>
on windows for this kind of thing, but on unix the only thing I can find is <ncurses.h>
, which uses a lot of C and doesn't support a lot of C++ functions. How can I move the console cursor to (x, y), while also being able to do object-oriented programming?
Edit: I'm trying to make simple games in C++ using the console as a display. I know it's not ideal to do so, but this is for a project that can't use Visual C++ or any other graphics. Think something like snake or minesweeper. I need to be able to cout
in different locations, without updating the entire screen in the process. It needs to be compatible with unix systems.
Upvotes: 1
Views: 1991
Reputation: 5668
One very simple way is through ANSI escape codes:
#include <iostream>
void moveCursor(std::ostream& os, int col, int row)
{
os << "\033[" << col << ";" << row << "H";
}
int main()
{
moveCursor(std::cout, 1,1);
std::cout << "X (1,1)";
moveCursor(std::cout, 13,8);
std::cout << "X (13,8)" << std::endl;
return 0;
}
The sequence <ESC>[
row ,
col H
(the escape character is ASCII 27 or octal '\033'
) performs absolut cursor positioning. On most common terminals this should place one "X" in the top-left corner, and the second in column 13, row 8 (counts are 1-based).
Edit: hvd’s comment is of course spot-on: This is very simple, but ncurses is complex for a reason. It is guaranteed to work more reliably and in a much wider variety of settings than a plain escape code. Depending on what you actually want to achieve, I agree with hvd that you should be very careful before picking this simple hack as the solution to your problem.
Upvotes: 2