Reputation: 174
Consider this code:
#include<stdio.h>
void main()
{
char a;
printf("scan: ");
scanf("%c",&a);
printf("\b back");
}
After the user presses Enter and makes the cursor go down, I want to move it back up so I can print the word "back" overwriting the word "scan". How do I do this?
Upvotes: 2
Views: 1630
Reputation:
You can use ANSI escape sequences: \033[<N>A
, where <N>
would be amount of lines you need to go up (in this case, one), so code would look like this:
#include<stdio.h>
main(void) {
char a;
printf("scan: ");
scanf("%c",&a);
printf("%c[1A back", 033);
}
Also, you shouldn't declare main as void
. Please note that escape sequences won't work in some terminals (like Windows cmd.exe or DOS without ANSI.SYS installed).
system("cls")
would be the worst method to solve the problem, and installing ncurses only to move cursor upwards is total overkill, because you always have this simple solution i presented above.
Whenever you'll want to read more about ANSI escape sequences, check this. If you want to rewind cursor to end of the line, check this:
#include<stdio.h>
main(void) {
char a;
printf("scan: ");
scanf("%c",&a);
printf("%c[1Ascan: %c back", 033, a);
}
You have to recreate line contents, tho. But it shouldn't be too problematic. It can be made easier with more advanced use of ANSI escape sequences, which you can check in link provided.
Upvotes: 4