将文本光标移动到特定的屏幕坐标

Move text cursor to particular screen coordinate?

本文关键字:屏幕坐标 文本 光标 移动      更新时间:2023-10-16

如何在 C 或 C++ 中将光标设置在控制台上的所需位置?

我记得一个名为 gotoxy(x,y) 的函数,但我认为它已被弃用。还有其他选择吗?

C 和 C++ 都没有屏幕或控制台的概念;它们只能看到字节流,这些字节流没有固有的显示特征。 有许多第三方 API(如 ncurses)可以帮助您做到这一点。

如果您想要一个快速肮脏的解决方案,并且您正在使用的终端了解 ANSI 转义序列,那么您可以执行以下操作:

printf("33[%d;%dH", row, col);

将光标移动到特定的行和列(其中左上角为 {1,1})。 不过,你最好使用ncurses(或你的平台的等效工具)。

使用 SetConsoleCursorPosition。

MSDN 库的同一部分中还有一堆其他函数。 其中一些也可能有用。

您可以使用

它将光标设置为屏幕上的特定坐标,然后只需使用 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 );
}

如果您谈论的是 ncurses 库,那么您所追求的功能是 move (row, column)

我使用了一个非常简单的方法。你不需要知道什么是句柄,除非你真的深入研究控制台应用程序,一个 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);
}
这是

在堆栈溢出...

`#include <stdio.h>
// ESC-H, ESC-J (I remember using this sequence on VTs)
#define clear() printf("33[H33[J")
//ESC-BRACK-column;row (same here, used on terminals on an early intranet)
#define gotoxy(x,y) printf("33[%d;%dH", (y), (x))
int main(void)
{
    clear();
    gotoxy(23, 12);
    printf("x");
    gotoxy(1, 24);
    return 0;
}`

对于 Windows: #include

#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 这样的库进行假设。