Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position the input text cursor in C?

Tags:

c

output

printing

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.

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

like image 462
It'sRainingMen Avatar asked Oct 17 '14 10:10

It'sRainingMen


People also ask

Which function is used to set the cursor at that particular position?

You can make a Windows API (application programming interface) call to a Microsoft Windows DLL (dynamic-link Library) to get and set the current cursor position. The current position can be obtained by using the GetCursorPos function in USER32. DLL.

Which method returns the current position of the cursor in the table?

cursorline = cursorline - 1.


2 Answers

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
like image 82
David Ranieri Avatar answered Oct 21 '22 10:10

David Ranieri


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.

like image 34
Cantfindname Avatar answered Oct 21 '22 11:10

Cantfindname