How to place the input cursor in C?

Here I have a very simple program:

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

Now I would like the result to look like this:

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

Where | * | this is a blinking cursor where the user enters their value.

Since C is a linear code, it will not print the field, and then ask about the output, it will print the top row and left column, and then after entering print the bottom row and right column.

So my question is: can I possibly move the field first and then return the function to the field?

+9
source share
3 answers

If you are under any 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 drawer symbols :

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

More information:

 man console_codes 
+18
source

In linux terminal, you can use terminal commands to move the cursor, e.g.

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

other similar teams:

 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 standardized solution, so your code will not be platform independent.

+9
source

The C language itself has no idea about a screen with a cursor. You will need to use the library that provides this support. is the most famous and widely available library for terminal management.

+1
source

Source: https://habr.com/ru/post/1204916/


All Articles