How to position the input text cursor in C?

后端 未结 3 707
野性不改
野性不改 2020-12-05 12:21

Here I have a very simple program:

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

Now, I would like the ou

相关标签:
3条回答
  • 2020-12-05 12:35

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

    #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;
    }
    

    Or using Box-drawing characters:

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

    More info:

    man console_codes
    
    0 讨论(0)
  • 2020-12-05 12:49

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

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

    other similar commands:

    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
    

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

    0 讨论(0)
  • 2020-12-05 12:50

    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. curses is the most well-known and widely available library for terminal control.

    0 讨论(0)
提交回复
热议问题