如何在 C 或 C++ 中将光标设置在控制台上的所需位置?
我记得一个名为 的函数gotoxy(x,y)
,但我认为它已被弃用。有没有其他选择?
MSDN 库的同一部分中还有许多其他功能。其中一些可能也很有用。
如果您在谈论ncurses库,您所追求的功能是move (row, column)
.
我使用一个非常简单的方法。除非您真正深入到控制台应用程序中,否则您不需要过度了解 HANDLE 是什么,COORD 对象位于 windows.h 标准库中,并且有两个成员数据整数 X 和 Y。0,0 是左上角角和 Y 增加向下屏幕。您可以使用此命令并继续使用 std::cout<< 打印您需要的任何内容。
#include <windows.h>
int main(void){
//initialize objects for cursor manipulation
HANDLE hStdout;
COORD destCoord;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
//position cursor at start of window
destCoord.X = 0;
destCoord.Y = 0;
SetConsoleCursorPosition(hStdout, destCoord);
}
您可以使用它来将光标设置到屏幕上的特定坐标,然后只需使用 cout<< 或 printf 语句在控制台上打印任何内容:
#include <iostream>
#include <windows.h>
using namespace std;
void set_cursor(int,int);
int main()
{
int x=0 , y=0;
set_cursor(x,y);
cout<<"Mohammad Usman Sajid";
return 0;
}
void set_cursor(int x = 0 , int y = 0)
{
HANDLE handle;
COORD coordinates;
handle = GetStdHandle(STD_OUTPUT_HANDLE);
coordinates.X = x;
coordinates.Y = y;
SetConsoleCursorPosition ( handle , coordinates );
}
这是在stackoverflow上...
`#include <stdio.h>
// ESC-H, ESC-J (I remember using this sequence on VTs)
#define clear() printf("\033[H\033[J")
//ESC-BRACK-column;row (same here, used on terminals on an early intranet)
#define gotoxy(x,y) printf("\033[%d;%dH", (y), (x))
int main(void)
{
clear();
gotoxy(23, 12);
printf("x");
gotoxy(1, 24);
return 0;
}`
对于 Windows:#include<windows.h>
#define cursor(x, y) SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), (COORD){x, y})
对于 Linux:
#define cursor(x,y) printf("\033[%d;%dH", x, y)
我想出了这个来设置光标。
#include <iostream>
void setPos(std::ostream& _os, const std::streamsize& _x, const std::streamsize& _y)
{
char tmp = _os.fill();
if(_y>0) {
_os.fill('\n');
_os.width(_y);
_os << '\n';
}
if(_x>0) {
_os.fill(' ');
_os.width(_x);
_os << ' ';
}
_os.flush();
_os.fill(tmp);
}
int main(int argc, char **argv)
{
setPos(std::cout, 5, 5);
std::cout << "foo" << std::endl;
return 0;
}
要做更多事情,您需要对分辨率或类似ncurses的库进行假设。