C语言 如何在C中定位输入文本光标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26423537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:28:24  来源:igfitidea点击:

How to position the input text cursor in C?

cprintingoutput

提问by It'sRainingMen

Here I have a very simple program:

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

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

Now, I would like the output to look like this:

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

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

Where, |*| is the blinking cursor where the user types their value.

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

Since C is a linear code, it won't print the box art, then ask for the output, it will print the top row and the left column, then after the input print the bottom row and right column.

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

So, my question is, could I possibly print the box first, then have a function take the cursor back into the box?

所以,我的问题是,我可以先打印盒子,然后让函数将光标带回盒子吗?

回答by David Ranieri

If you are under some Unix terminal (xterm, gnome-terminal...), you can use console codes:

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

#include <stdio.h>

#define clear() printf("3[H3[J")
#define gotoxy(x,y) printf("3[%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;
}

Or using Box-drawing characters:

或使用Box-drawing 字符

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

More info:

更多信息:

man console_codes

回答by Cantfindname

In the linux terminal you may use terminal commands to move your cursor, such as

在 linux 终端中,您可以使用终端命令来移动光标,例如

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

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

other similar commands:

其他类似的命令:

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

Keep in mind that this is not a standardised solution, and therefore your code will not be platform independent.

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

回答by luser droog

The C language itself doesn't have any notion of a screen with a cursor. You'll have to use some kind of library that provides this support. cursesis the most well-known and widely available library for terminal control.

C 语言本身没有带光标的屏幕的任何概念。您必须使用某种提供这种支持的库。curses是最著名和最广泛使用的终端控制库。