【问题标题】:How to position the input text cursor in C?如何在C中定位输入文本光标?
【发布时间】:2014-12-12 22:47:27
【问题描述】:

这里我有一个非常简单的程序:

 printf("Enter your number in the box below\n");
 scanf("%d",&number);

现在,我希望输出如下所示:

 Enter your number in the box below
 +-----------------+
 | |*|             |
 +-----------------+

在哪里,|*|是用户输入值的闪烁光标。

由于C是线性代码,它不会打印box art,然后要求输出,它会打印顶行和左列,然后在输入后打印底行和右列。

所以,我的问题是,我是否可以先打印该框,然后让一个函数将光标带回该框?

【问题讨论】:

  • @SouravGhosh 好的,这是相对位移而不是绝对位移吗?
  • 这在标准 C99 中是不可能的。在某些操作系统上,您可以使用一些库,例如 ncursesreadline

标签: c printing output


【解决方案1】:

如果你在某个 Unix 终端下(xtermgnome-terminal ...),你可以使用控制台代码:

#include <stdio.h>

#define clear() printf("\033[H\033[J")
#define gotoxy(x,y) printf("\033[%d;%dH", (y), (x))

int main(void)
{
    int number;

    clear();
    printf(
        "Enter your number in the box below\n"
        "+-----------------+\n"
        "|                 |\n"
        "+-----------------+\n"
    );
    gotoxy(2, 3);
    scanf("%d", &number);
    return 0;
}

或者使用Box-drawing characters:

printf(
    "Enter your number in the box below\n"
    "╔═════════════════╗\n"
    "║                 ║\n"
    "╚═════════════════╝\n"
);

更多信息:

man console_codes

【讨论】:

  • 请注意,#define gotoxy(x,y) printf("\033[%d;%dH", (x), (y)) 实际上应该是 #define gotoxy(x,y) printf("\033[%d;%dH", (y), (x))。你切换了 x 和 y!
【解决方案2】:

在linux终端你可以使用终端命令来移动你的光标,比如

printf("\033[8;5Hhello"); // Move to (8, 5) and output hello

其他类似的命令:

printf("\033[XA"); // Move up X lines;
printf("\033[XB"); // Move down X lines;
printf("\033[XC"); // Move right X column;
printf("\033[XD"); // Move left X column;
printf("\033[2J"); // Clear screen

请记住,这不是一个标准化的解决方案,因此您的代码不会独立于平台。

【讨论】:

  • +1 这是一个很好的答案,它还解释了其他可以更改光标的命令。我认为这应该是答案,因为它既快又短又有用。
  • 请注意,在您的第一条语句 (8, 5) -> 第 8 行,第 5 列!我花了一分钟才弄清楚为什么我的程序没有按预期工作......无论如何,谢谢! +1
【解决方案3】:

C 语言本身没有任何带有光标的屏幕的概念。您必须使用某种提供此支持的库。 是最广为人知的终端控制库。

【讨论】:

  • 确实是语言本身,但大多数控制台为此具有各种功能。并且curses 使用转义序列,就像其他人公开的一样。
【解决方案4】:
#include <conio.h>

void main() {
    char d;
    cprintf("*---------*\n\r|         |\n\r*---------*");
    gotoxy(4,2);
    scanf("%c",&d);
}

这适用于所有操作系统

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多