10

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

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

4

8 回答 8

11

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

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

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

将光标移动到特定的行和列(左上角为 {1,1})。不过,您最好使用 ncurses(或您平台的等价物)。

于 2012-05-01T18:44:19.280 回答
6

使用SetConsoleCursorPosition

MSDN 库的同一部分中还有许多其他功能。其中一些可能也很有用。

于 2012-05-02T02:16:07.443 回答
3

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

于 2012-05-01T17:53:39.680 回答
2

我使用一个非常简单的方法。除非您真正深入到控制台应用程序中,否则您不需要过度了解 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);
}
于 2016-05-25T19:44:26.010 回答
1

您可以使用它来将光标设置到屏幕上的特定坐标,然后只需使用 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 );
}
于 2020-06-02T07:36:13.260 回答
1

这是在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;
}`
于 2019-12-25T03:18:46.147 回答
1

对于 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)

于 2021-10-22T21:33:27.807 回答
-1

我想出了这个来设置光标。

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

于 2012-05-01T18:21:03.620 回答