如何将输入文本光标定位在C?

It'*_*Men 9 c printing output

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

 printf("Enter your number in the box below\n");
 scanf("%d",&number);
Run Code Online (Sandbox Code Playgroud)

现在,我希望输出看起来像这样:

 Enter your number in the box below
 +-----------------+
 | |*|             |
 +-----------------+
Run Code Online (Sandbox Code Playgroud)

哪里,|*| 是用户键入其值的闪烁光标.

由于C是一个线性代码,它不会打印盒子艺术,然后要求输出,它将打印顶行和左列,然后输入后打印底行和右列.

所以,我的问题是,我可以先打印盒子,然后有一个功能将光标放回盒子里吗?

Dav*_*eri 20

如果你在某个Unix终端(xterm,gnome-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;
}
Run Code Online (Sandbox Code Playgroud)

或者使用Box-drawing字符:

printf(
    "Enter your number in the box below\n"
    "???????????????????\n"
    "?                 ?\n"
    "???????????????????\n"
);
Run Code Online (Sandbox Code Playgroud)

更多信息:

man console_codes
Run Code Online (Sandbox Code Playgroud)

  • 注意 ```#define gotoxy(x,y) printf("\033[%d;%dH", (x), (y))``` 实际上应该是 ```#define gotoxy(x,y) ) printf("\033[%d;%dH", (y), (x))```. 你交换了 x 和 y! (3认同)

Can*_*ame 9

在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
Run Code Online (Sandbox Code Playgroud)

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

  • +1这是一个很好的答案,它还解释了其他可能更改光标的命令,从而超越了其他所有内容。我认为这应该是答案,因为它既快速又短而有用。 (2认同)